<?php





namespace app\admin\model;





use app\admin\validate\Shop;

use app\admin\struct\ShopStruct;

use think\facade\Db;

use think\Model;

use think\model\concern\SoftDelete;

use think\model\relation\HasOne;

use app\crm\model\ReserveandLost;



class ShopModel extends Common

{

    use ShopStruct;



    use SoftDelete;



    const FIELD = [

        'id', 'shop_id', 'shop_owner', 'type', 'area', 'keycode', 'bed_num', 'deptno', 'monthly_fee', 'open_at',

        'close_end_at', 'close_start_at', 'remark', 'introduce', 'mobile', 'deptno', 'sex', 'shop_name',

        'shop_phone', 'market_id', 'region_id', 'status', 'created_at'

    ];

    // 设置字段信息

    protected $schema = [



    ];

    /**

     * 类型转换

     * @var string[]

     */

    protected $type = [



    ];

    /**

     * @var string

     */

    protected $name = 'shop';



    protected $defaultSoftDelete = 0;



    protected $autoWriteTimestamp = true;



    /**

     * 驼峰格式转换

     * @var bool

     */

    protected $convertNameToCamel = true;



    protected $json = ['relation_shop'];



    protected $jsonAssoc = true;



    protected $fail;



    protected $append = ['personCount', 'customerCount', 'serviceCount'];



    /**

     * @return int

     * @author ran

     * @date 2021-11-17 10:24

     * mailbox 466180170@qq.com

     */

    public function getServiceCountAttr()

    {

        return $this->service()->count();

    }



    /**

     * @return int

     * @author ran

     * @date 2021-11-17 10:24

     * mailbox 466180170@qq.com

     */

    public function getPersonCountAttr()

    {

        return $this->person()->where('status', 1)->count();

    }



    /**

     * @return int

     * @author ran

     * @date 2021-11-17 10:24

     * mailbox 466180170@qq.com

     */

    public function getCustomerCountAttr()

    {

        return $this->customer()->count();

    }



    /**

     * @return HasOne

     * @author ran

     * @date 2021-09-22 18:15

     * mailbox 466180170@qq.com

     */

    public function shopType()

    {

        return $this->hasOne(ShopTypeModel::class, 'id', 'type');

    }



    /**

     * @return HasOne

     * @author ran

     * @date 2021-09-22 18:15

     * mailbox 466180170@qq.com

     */

    public function market()

    {

        return $this->hasOne(MarketModel::class, 'id', 'market_id');

    }



    /**

     * @return HasOne

     * @author ran

     * @date 2021-09-22 18:15

     * mailbox 466180170@qq.com

     */

    public function region()

    {

        return $this->hasOne(RegionModel::class, 'id', 'region_id');

    }



    /**

     * @return HasOne

     * @author ran

     * @date 2021-09-22 18:15

     * mailbox 466180170@qq.com

     */

    public function user()

    {

        return $this->hasOne(User::class, 'shop_id', 'shop_id');

    }



    /**

     * @return \think\model\relation\HasMany

     * @author ran

     * @date 2021-11-17 10:15

     * mailbox 466180170@qq.com

     */

    public function person()

    {

        return $this->hasMany(PersonModel::class, 'shop_id', 'shop_id')->field('shop_id,name');

    }



    /**

     * @return \think\model\relation\HasMany

     * @author ran

     * @date 2021-11-17 10:15

     * mailbox 466180170@qq.com

     */

    public function customer()

    {

        return $this->hasMany(CustomerModel::class, 'shop_id', 'shop_id')->field('shop_id,name');

    }



    /**

     * @return \think\model\relation\HasMany

     * @author ran

     * @date 2021-11-17 10:15

     * mailbox 466180170@qq.com

     */

    public function service()

    {

        return $this->hasMany(ServiceModel::class, 'shop_id', 'shop_id')->field('shop_id,name');

    }



    /**

     * @return array

     * @author ran

     * @date 2021-10-16 16:54

     * mailbox 466180170@qq.com

     */

    private function getShopCondition(array $request)

    {

        $where = [];

        $shopName = isset($request['shopName']) && trim($request['shopName']) ? trim($request['shopName']) : '';

        $keycode = isset($request['keycode']) && intval($request['keycode']) ? intval($request['keycode']) : 0;

        $shopOwner = isset($request['shopOwner']) && trim($request['shopOwner']) ? trim($request['shopOwner']) : '';

        $type = isset($request['type']) && trim($request['type']) ? trim($request['type']) : 0;

        $marketId = isset($request['marketId']) && intval($request['marketId']) ? intval($request['marketId']) : 0;

        $regionId = isset($request['regionId']) && intval($request['regionId']) ? intval($request['regionId']) : 0;

        $shopId = isset($request['shopId']) && intval($request['shopId']) ? intval($request['shopId']) : 0;

        $status = isset($request['status']) && intval($request['status']) ? intval($request['status']) : 0;

        $shopName && array_push($where, ['shop_name', 'like', '%' . $shopName . '%']);

        $keycode && array_push($where, ['keycode', '=', $keycode]);

        $shopOwner && array_push($where, ['shop_owner', '=', $shopOwner]);

        $type && array_push($where, ['type', '=', $type]);

        $marketId && array_push($where, ['market_id', '=', $marketId]);

        $regionId && array_push($where, ['region_id', '=', $regionId]);

        $status && array_push($where, ['status', '=', $status]);

        $shopId && array_push($where, ['shop_id', '=', $shopId]);

        return $where;

    }



    /**

     * 创建店铺资源

     * @param array $request

     * @return false

     * @author ran

     * @date 2021-09-16 15:43

     * mailbox 466180170@qq.com

     */

    public function createShopResource(array $request)

    {

        $validate = new Shop();

        if (!$validate->scene('create')->check($request)) {

            $this->error = $validate->getError();

            return false;

        }

        $request['shopId'] = getUniqueShopNumberCode(14);

        try {

            $re =$this->where('shop_mobile',$request['shopMobile'])->find();

            if($re){

                $this->error = '店铺店长账户手机号不能重复,请更换手机号';

                return false;

            }

            $res = $this->create($request);

            if ($res->id) {

                if ($this->createShopAdminUser($request) === true) {

                    return true;

                }

                $this->error = '店铺用户入库失败';

                return false;

            }

            $this->error = '店铺入库失败';

            return false;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

    }



    /**

     * 更新店铺资源

     * @param array $request

     * @return false

     * @author ran

     * @date 2021-09-16 15:43

     * mailbox 466180170@qq.com

     */

    public function updateShopResource(array $request)

    {

        $validate = new Shop();

        if (!$validate->scene('update')->check($request)) {

            $this->error = $validate->getError();

            return false;

        }

        try {

            $this->update($request, ['shop_id' => $request['shopId']]);

            $this->updateShopAdminUser($request);

            return true;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

    }



    /**

     * 更新店铺资源

     * @param array $request

     * @return false

     * @author ran

     * @date 2021-09-16 15:43

     * mailbox 466180170@qq.com

     */

    public function updateShopPersonResource(array $request)

    {

        $validate = new Shop();

        if (!$validate->scene('update')->check($request)) {

            $this->error = $validate->getError();

            return false;

        }

        try {

            $this->update($request, ['shop_id' => $request['shopId']]);

            $this->updateShopAdminUser($request);

            return true;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

    }



    /**

     * 获取店铺列表

     * @author ran

     * @date 2021-09-22 16:37

     * mailbox 466180170@qq.com

     */

    public function getShopAdminListResource(array $shopIds, int $page, int $limit, $request)

    {

        $where = $this->getShopCondition($request);

        $scene =$request['scene']??'shop';

        switch ($scene) {

            case 'customer':

                $connect = $this->where($where)->where('status','<>',3);

                break;

            default:

                $connect = $this->where($where)->where('status','<>',3)

                    ->when($shopIds ?? [], function ($query) use ($shopIds) {

                        return $query->whereIn('shop_id', $shopIds);

                    });

                break;

        }

        $count = $connect->count();

        $list = $connect->page($page, $limit)->select();

        foreach ($list as $key => $value) {

            $list[$key]['saleAmt'] = 30;

            $list[$key]['customerNum'] = 1000;

        }

        return [

            'list' => $list,

            'dataCount' => $count

        ];

    }



    /**

     * 获取店铺信息

     * @param int $shopId

     * @author ran

     * @date 2021-10-18 9:02

     * mailbox 466180170@qq.com

     */

    public function getShopAdminInfoResource(int $shopId)

    {

        $adminUser = new User();

        $lastLoginAt = $adminUser->where('shop_id', $shopId)->value('last_login_at');

        $info = $this->where('shop_id', $shopId)->find();

        $info['lastLoginAt'] = $lastLoginAt;

        $info['saleNum'] = 0;

        $info['noWarning'] = 0;

        $info['noAccountability'] = 0;

        $info['visitNum'] = 0;

        $info['returnTimes'] = 0;

        return $info;

    }

	/**

	     * 获取登录人信息

	     * @param int $shopId

	     * @author ran

	     * @date 2021-10-18 9:02

	     * mailbox 466180170@qq.com

	     */

	    public function getUserInfoResource($user_id)

	    {
            $shop_where = [];

            $market_names = ['郑州市场','中医院市场'];

            array_push($shop_where,['market_name','in',$market_names]);

            array_push($shop_where,['type','=','1']);

            $shop_list = Db::name('shop')->where($shop_where)->column('shop_id');

	        $user_info = Db::name('admin_user')->where('id',$user_id)->select()->toArray();

	        if(!empty($user_info[0]['shop_id'])){

	            $shop_type = Db::name('shop')->where('shop_id',$user_info[0]['shop_id'])->value('shop_type');

                $is_use = in_array($user_info[0]['shop_id'],$shop_list) ? '1' : '0';

	        }else{

	            $shop_type = '2';

                $is_use = '1';

	        }

            $data['shop_type'] = $shop_type;
            $data['is_use'] = $is_use;

	        return $data;

	    }

    /**

     * 根据店铺ID获取关联市场

     * @author ran

     * @date 2021-11-26 10:38

     * mailbox 466180170@qq.com

     */

    public function readAdminShopRelationMarketByShopId(int $shopId)

    {

        $info = $this->where('shop_id', $shopId)->find();

        $market = [[

            'marketId' => $info['marketId'],

            'marketName' => $info['marketName'],

            'marketKingdeeCode' => $info['marketKingdeeCode']

        ]];

        if (!empty($info['relation_market_id'])) {

            $marketModel = new MarketModel();

            $marketKingdeeCode=$marketModel->where('id',$info['relation_market_id'])->value('kingdee_code');

            $relationMarket = [

                'marketId' => $info['relation_market_id'] ?? '',

                'marketName' => $info['relation_market_name'] ?? '',

                'marketKingdeeCode' => $marketKingdeeCode

            ];

            array_push($market, $relationMarket);

        }

        return $market;

    }



    /**

     * 创建店铺用户

     * @author ran

     * @date 2021-09-25 14:49

     * mailbox 466180170@qq.com

     */

    protected function createShopAdminUser(array $request)

    {

        $adminUser = new User();

        $salt = substr(md5(time()), 0, 4);

        $data = [

            'shop_id' => $request['shopId'],

            'username' => $request['shopMobile'],

            'realname' => $request['shopOwner'],

            'salt' => $salt,

            'password' => user_md5($request['password'], $salt, $request['shopMobile']),

            'type' => 2,

            'sex' => $request['sex'],

            'mobile' => $request['shopMobile'],

            'create_time' => time()

        ];

        try {

            $res=$adminUser->create($data);

            if ($res->id) {

                $accessModel = new Access();

                $data = [

                    'user_id' => $res->id,

                    'group_id' => 2

                ];

                $accessModel->create($data);

            }

            return true;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

    }



    /**

     * 更新店铺用户

     * @author ran

     * @date 2021-09-25 14:49

     * mailbox 466180170@qq.com

     */

    protected function updateShopAdminUser(array $request)

    {

        $adminUser = new User();

        $salt = substr(md5(time()), 0, 4);

        $data = [

            'username' => $request['shopMobile'],

            'sex' => $request['sex'],

            'mobile' => $request['shopMobile'],

        ];

        if (!empty($request['password'])) {

            $data['salt'] = $salt;

            $data['password'] = user_md5($request['password'], $salt, $request['shopMobile']);

        }

        try {

            $adminUser->update($data, ['shop_id' => $request['shopId'],'type'=>2]);

            return true;

        } catch (\Exception $e) {

            $this->fail = $e->getMessage();

            return false;

        }

    }



    /**

     * 店铺资源导出

     * @author ran

     * @date 2021-12-01 11:56

     * mailbox 466180170@qq.com

     */

    public function exportAdminShopListResoure(array $shopIds, array $request, array $ids)

    {

        $where = $this->getShopCondition($request);

        $field = [

            'id', 'shop_id', 'shop_name', 'type_name', 'market_name',

            'region_name', 'province_name', 'city_name', 'status', 'shop_owner',

            'shop_mobile'

        ];

        $list = $this->where($where)->field($field)

            ->when($ids ?? [], function ($query) use ($ids) {

                return $query->whereIn('id', $ids);

            })

            ->when($shopIds ?? [], function ($query) use ($shopIds) {

                return $query->whereIn('shop_id', $shopIds);

            })->page(1, 10000)->select()->toArray();

        foreach ($list as &$v) {

            $v['areaName'] = $v['provinceName'] . '-' . $v['cityName'];

            $v['statusDesc'] = $v['status'] == 1 ? '运营中' : '永久关闭';

        }

        $callName = [

            'id' => '店铺id', 'shopId' => '店铺编码', 'shopName' => '店铺名称',

            'typeName' => '类型', 'marketName' => '归属市场', 'regionName' => '归属大区',

            'areaName' => '所在省-市', 'statusDesc' => '状态', 'shopOwner' => '店长',

            'shopMobile' => '店长电话',

        ];

        $downUrl = exportExcelData('shop', $callName, $list, 'xlsx', 1);

        return [

            'url' => 'http://' . $_SERVER['HTTP_HOST'] . $downUrl,

        ];

    }



    /**

     * @param $shopIds

     * @param int $page

     * @param int $limit

     * @param $request

     * @return array

     * @author ran

     * @date 2022-01-18 17:35

     * mailbox 466180170@qq.com

     */

    public function readAdminShopAchievementStatistics($shopIds,int $page, int $limit,$request)

    {
        $s =$request['start_time'] ?? 0;

        $e =$request['end_time'] ?? 0;

        $type = $request['type'];


        $startTime = strtotime($s);

        $endTime = strtotime($e)+86399;

        $startMonthTime = strtotime(date('Y-m',$startTime));

        $endMonthTime = strtotime(date('Y-m',$endTime));

        $where = [];
        array_push($where,['status','=',1]);

        if(!empty($type))
        {
            array_push($where,['type','=',$type]);

        }
        $connect = Db::name('shop')

            ->field('shop_id as shopId,shop_name as shopName,market_name as marketName,market_id as marketId, shop_type')

            //->where([['type','=', 1],['status','=',1],['market_id','in',[20,21,22,23,24]]])
            //->where([['type','=', 1],['status','=',1]])
            ->where($where)

            ->when($shopIds ?? [], function ($query) use ($shopIds) {

                return $query->whereIn('shop_id', $shopIds);

            });

        $count =$connect-> count();

        //$list =$connect->page($page, $limit)->select();
        $list =$connect->select();

        $list =empty($list) ? [] : $list->toArray();
        //门店当月任务

        $task =Db::name('shop_task')->field('sum(price) as price,sum(price_base) as price_base,shop_id')

            ->where('month','>=',$startMonthTime)

            ->where('month','<=',$endMonthTime)

            ->group('shop_id')->select()->toArray();

        //门店当月市场任务

        $marketTask =Db::name('shop_task')->field('sum(price) as price,sum(price_base) as price_base,market_id')

            ->where('month','>=',$startMonthTime)

            ->where('month','<=',$endMonthTime)

            ->group('market_id')->select()->toArray();

        //市场达成金额

        $marketReach =Db::name('shop_refund_order')

            ->field('sum(pay_amount) as price,market_id')

            ->where('type',3)

            ->where('status','<>',3)

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })->group('market_id')->select()->toArray();

        //数据绑定

        $marketReachs =array_column($marketReach,null,'market_id');

        $marketTasks=array_column($marketTask,null,'market_id');

        $tasks=array_column($task,null,'shop_id');

        $heji = [];

        $heji['marketName'] = "合计";

        $heji['shopName']   = "";

        $amountAll =$this->amountMoneyAllAll($startTime,$endTime);

        $scarMoneyAll =$this->sumShopPayMoneyNewMZAll('Bh',$startTime,$endTime);

        $projectMoneyAll =$this->sumShopPayMoneyNewMZAll('XM',$startTime,$endTime);

        $projectStMoneyAll = $this->sumShopPayMoneyNewMZAll('STXM',$startTime,$endTime); //身体项目

        $projectPfMoneyAll = $this->sumShopPayMoneyNewMZAll('PFXM',$startTime,$endTime); //皮肤项目

        $qcdMoneyAll =$this->sumShopPayMoneyNewMZAll('QCD',$startTime,$endTime); // 青春痘

        $hfpMoneyAll =$this->sumShopPayMoneyNewMZAll('HFP',$startTime,$endTime); // 护肤品


        $referralMoneyAllOne =$this->referralMoneyAll(1,$startTime,$endTime);

        $referralMoneyAllTwo =$this->referralMoneyAll(2,$startTime,$endTime);

        $scarMoneyAllOne =$this->sumShopPayMoneyNewAll('Bh',1,$startTime,$endTime);

        $scarMoneyAllTwo =$this->sumShopPayMoneyNewAll('Bh',2,$startTime,$endTime);

        $projectMoneyAllOne =$this->sumShopPayMoneyNewAll('XM',1,$startTime,$endTime);

        $projectMoneyAllTwo =$this->sumShopPayMoneyNewAll('XM',2,$startTime,$endTime);

        $projectStMoneyAllOne = $this->sumShopPayMoneyNewAll('STXM',1,$startTime,$endTime); //身体项目

        $projectStMoneyAllTwo = $this->sumShopPayMoneyNewAll('STXM',2,$startTime,$endTime); //身体项目

        $projectPfMoneyAllOne = $this->sumShopPayMoneyNewAll('PFXM',1,$startTime,$endTime); //皮肤项目

        $projectPfMoneyAllTwo = $this->sumShopPayMoneyNewAll('PFXM',2,$startTime,$endTime); //皮肤项目

        // 青春痘
        $qcdMoneyAllOne =$this->sumShopPayMoneyNewAll('QCD',1,$startTime,$endTime);

        $qcdMoneyAllTwo =$this->sumShopPayMoneyNewAll('QCD',2,$startTime,$endTime);

        // 护肤品
        $hfpMoneyAllOne =$this->sumShopPayMoneyNewAll('HFP',1,$startTime,$endTime);

        $hfpMoneyAllTwo =$this->sumShopPayMoneyNewAll('HFP',2,$startTime,$endTime);


        // print_r($referralMoneyAllOne);
        // print_r($referralMoneyAllTwo);
        // exit;

        foreach ($list as $key=>$value){
            //实收金额业绩计算
            // $amount =$this->amountMoneyAll($value['shopId'],$startTime,$endTime);
            $amount = empty($amountAll[$value['shopId']])?0:$amountAll[$value['shopId']];

            //转诊金额计算  川渝市场和门诊的转诊  都是 默认 0 不计算 对接财务确定；2022-07-24
            if($value['marketId'] == 8 || $value['marketId'] == 9 || $value['marketId'] == 10|| $value['marketId'] == 11  ){
                //$referralMoney =0;
                //疤痕业绩计算--川渝市场
                // $scarMoney =$this->sumShopPayMoneyNewMZ('Bh',$value['shopId'],$value['shop_type'],$startTime,$endTime);
                $scarMoney = empty($scarMoneyAll[$value['shopId']])?0:$scarMoneyAll[$value['shopId']];// 疤痕
                // $projectMoney =$this->sumShopPayMoneyNewMZ('XM',$value['shopId'],$value['shop_type'],$startTime,$endTime);
                $projectMoney = empty($projectMoneyAll[$value['shopId']])?0:$projectMoneyAll[$value['shopId']];// 项目

                $projectStMoney = empty($projectStMoneyAll[$value['shopId']])?0:$projectStMoneyAll[$value['shopId']];// 身体项目

                $projectPfMoney = empty($projectPfMoneyAll[$value['shopId']])?0:$projectPfMoneyAll[$value['shopId']];// 皮肤项目

                $qcdMoney = empty($qcdMoneyAll[$value['shopId']])?0:$qcdMoneyAll[$value['shopId']];// 青春痘

                $hfpMoney = empty($hfpMoneyAll[$value['shopId']])?0:$hfpMoneyAll[$value['shopId']];// 护肤品
            }else{
                // $referralMoney =$this->referralMoney($value['shopId'],$value['shop_type'],$startTime,$endTime);

                if($value['shop_type'] == 1)
                {
                    //$referralMoney = empty($referralMoneyAllOne[$value['shopId']])?0:$referralMoneyAllOne[$value['shopId']];
                    $scarMoney = empty($scarMoneyAllOne[$value['shopId']])?0:$scarMoneyAllOne[$value['shopId']];
                    $projectMoney = empty($projectMoneyAllOne[$value['shopId']])?0:$projectMoneyAllOne[$value['shopId']];

                    $projectStMoney = empty($projectStMoneyAllOne[$value['shopId']])?0:$projectStMoneyAllOne[$value['shopId']];// 身体项目

                    $projectPfMoney = empty($projectPfMoneyAllOne[$value['shopId']])?0:$projectPfMoneyAllOne[$value['shopId']];// 皮肤项目

                    $qcdMoney = empty($qcdMoneyAllOne[$value['shopId']])?0:$qcdMoneyAllOne[$value['shopId']];// 青春痘
                    $hfpMoney = empty($hfpMoneyAllOne[$value['shopId']])?0:$hfpMoneyAllOne[$value['shopId']];// 护肤品
                }else{
                    //$referralMoney = empty($referralMoneyAllTwo[$value['shopId']])?0:$referralMoneyAllTwo[$value['shopId']];
                    $scarMoney = empty($scarMoneyAllTwo[$value['shopId']])?0:$scarMoneyAllTwo[$value['shopId']];
                    $projectMoney = empty($projectMoneyAllTwo[$value['shopId']])?0:$projectMoneyAllTwo[$value['shopId']];

                    $projectStMoney = empty($projectStMoneyAllTwo[$value['shopId']])?0:$projectStMoneyAllTwo[$value['shopId']];// 身体项目

                    $projectPfMoney = empty($projectPfMoneyAllTwo[$value['shopId']])?0:$projectPfMoneyAllTwo[$value['shopId']];// 皮肤项目

                    $qcdMoney = empty($qcdMoneyAllTwo[$value['shopId']])?0:$qcdMoneyAllTwo[$value['shopId']];// 青春痘
                    $hfpMoney = empty($hfpMoneyAllTwo[$value['shopId']])?0:$hfpMoneyAllTwo[$value['shopId']];// 护肤品
                }

            }


            // 转诊业绩 新的计算规则

            $bhoxmAmount = bcadd($scarMoney,$projectMoney,2); //疤痕+项目业绩合计
            $qcdohfpAmount = bcadd($qcdMoney,$hfpMoney,2); //青春痘+护肤品业绩合计

            $bohtotalAmount = bcadd($bhoxmAmount,$qcdohfpAmount,2);

            $referralMoney = bcsub($bohtotalAmount,$amount,2); //疤痕+项目+护肤品+青春痘  减去 实收金额



            $shopTask =$tasks[$value['shopId']]['price']??0;
            $shopTaskBase =$tasks[$value['shopId']]['price_base']??0;


            //$shopReachRate =$shopTask==0?'0%':bcmul(bcdiv($amount,$shopTask,2),'100',2).'%'; // 门店达成金额/门店任务
            $shopReachRate =$shopTask==0?'0%':bcmul(bcdiv(bcadd($amount,$referralMoney,2),$shopTask,2),'100',2).'%'; // 门店达成金额/门店任务

            $shopReachRateBase =$shopTaskBase==0?'0%':bcmul(bcdiv(bcadd($amount,$referralMoney,2),$shopTaskBase,2),'100',2).'%'; // 基础任务

            $list[$key]['amount'] = $amount;

            $heji['amount'] = isset($heji['amount']) ? bcadd($heji['amount'],$list[$key]['amount'],2) : $list[$key]['amount'];

            $list[$key]['referralMoney'] = $referralMoney;

            $heji['referralMoney'] = isset($heji['referralMoney']) ? bcadd($heji['referralMoney'],$list[$key]['referralMoney'],2) : $list[$key]['referralMoney'];

            $list[$key]['scarMoney'] = $scarMoney;

            $heji['scarMoney'] = isset($heji['scarMoney']) ? bcadd($heji['scarMoney'],$list[$key]['scarMoney'],2) : $list[$key]['scarMoney'];

            $list[$key]['projectMoney'] =$projectMoney;

            $heji['projectMoney'] = isset($heji['projectMoney']) ? bcadd($heji['projectMoney'],$list[$key]['projectMoney'],2) : $list[$key]['projectMoney'];

            $list[$key]['skinItem'] =$projectPfMoney;   //皮肤项目

            $heji['skinItem'] = isset($heji['skinItem']) ? bcadd($heji['skinItem'],$list[$key]['skinItem'],2) : $list[$key]['skinItem'];

            $list[$key]['physicalEvent'] =$projectStMoney;  //身体项目

            $heji['physicalEvent'] = isset($heji['physicalEvent']) ? bcadd($heji['physicalEvent'],$list[$key]['physicalEvent'],2) : $list[$key]['physicalEvent'];

            // 青春痘
            $list[$key]['qcdMoney'] = $qcdMoney;

            $heji['qcdMoney'] = isset($heji['qcdMoney']) ? bcadd($heji['qcdMoney'],$list[$key]['qcdMoney'],2) : $list[$key]['qcdMoney'];

            // 护肤品
            $list[$key]['hfpMoney'] = $hfpMoney;

            $heji['hfpMoney'] = isset($heji['hfpMoney']) ? bcadd($heji['hfpMoney'],$list[$key]['hfpMoney'],2) : $list[$key]['hfpMoney'];

            $list[$key]['achievementMoney'] = bcadd($amount,$referralMoney,2);//$amount+$referralMoney;

            $heji['achievementMoney'] = isset($heji['achievementMoney']) ? bcadd($heji['achievementMoney'],$list[$key]['achievementMoney'],2) : $list[$key]['achievementMoney'];

            $list[$key]['shopTask'] = $shopTask;
            $list[$key]['shopTaskBase'] = $shopTaskBase;

            $heji['shopTask'] = isset($heji['shopTask']) ? bcadd($heji['shopTask'],$list[$key]['shopTask'],2) : $list[$key]['shopTask'];
            $heji['shopTaskBase'] = isset($heji['shopTaskBase']) ? bcadd($heji['shopTaskBase'],$list[$key]['shopTaskBase'],2) : $list[$key]['shopTaskBase'];

            $list[$key]['shopReachRate'] = $shopReachRate;

            $list[$key]['shopReachRateBase'] = $shopReachRateBase;

            //$heji['shopReachRate'] = isset($heji['shopReachRate']) ? bcadd($heji['shopReachRate'],$list[$key]['shopReachRate'],2) : $list[$key]['shopReachRate'];

            $list[$key]['timeReachRate'] = 0;

        }
        $item=[];
        foreach($list as $v) {
            if (!isset($item[$v['marketId']])) {
                $item[$v['marketId']] = $v;
            } else {
                $item[$v['marketId']]['achievementMoney'] += $v['achievementMoney'];
            }
        }
        foreach ($list as $key=>$value){
            $marketReach =round($item[$value['marketId']]['achievementMoney'],2);
            $marketTask =$marketTasks[$value['marketId']]['price']??0;
            $marketTaskBase =$marketTasks[$value['marketId']]['price_base']??0;
            $marketReachRate =$marketTask==0?'0%':bcmul(bcdiv($marketReach,$marketTask,2),'100',2).'%';
            $marketReachRateBase =$marketTaskBase==0?'0%':bcmul(bcdiv($marketReach,$marketTaskBase,2),'100',2).'%';
            $list[$key]['marketTask'] = $marketTask;
            $list[$key]['marketTaskBase'] = $marketTaskBase;
            $list[$key]['marketReachRate'] = $marketReachRate;
            $list[$key]['marketReachRateBase'] = $marketReachRateBase;
            //$heji['marketReachRate'] = isset($heji['marketReachRate']) ? bcadd($heji['marketReachRate'],$list[$key]['marketReachRate'],2) : $list[$key]['marketReachRate'];
            $list[$key]['marketReach'] = round($item[$value['marketId']]['achievementMoney'],2);
        }

        $heji['shopReachRate'] =$heji['shopTask']>0 ? bcmul(bcdiv($heji['achievementMoney'],$heji['shopTask'],2),'100',2).'%': '0%';
        $heji['shopReachRateBase'] =$heji['shopTaskBase']>0 ? bcmul(bcdiv($heji['achievementMoney'],$heji['shopTaskBase'],2),'100',2).'%': '0%';

        /* echo '<pre>';
        print_r($list);exit; */

        $days=date('t', time());

        $today=date('d', time());


        $data3= [];
        foreach ($list as $value)
        {
            if(empty($data3[$value['marketName']]))
            {
                $data3[$value['marketName']]['marketName']=$value['marketName'];
                $data3[$value['marketName']]['marketTask']=$value['marketTask'];
                $data3[$value['marketName']]['marketReachRate']=$value['marketReachRate'];
                $data3[$value['marketName']]['marketReach']=$value['marketReach'];
                $data3[$value['marketName']]['marketTaskBase']=$value['marketTaskBase'];
                $data3[$value['marketName']]['marketReachRateBase']=$value['marketReachRateBase'];
                $data3[$value['marketName']]['list']=[];

                $heji['marketTask'] = isset($heji['marketTask']) ? bcadd($heji['marketTask'],$value['marketTask'],2) : $value['marketTask'];
                $heji['marketTaskBase'] = isset($heji['marketTaskBase']) ? bcadd($heji['marketTaskBase'],$value['marketTaskBase'],2) : $value['marketTaskBase'];
                $heji['marketReach'] = isset($heji['marketReach']) ? bcadd($heji['marketReach'],$value['marketReach'],2) : $value['marketReach'];
            }
            array_push($data3[$value['marketName']]['list'],$value);
        }
        $heji['marketReachRate'] =$heji['marketTask']>0 ? bcmul(bcdiv($heji['achievementMoney'],$heji['marketTask'],2),'100',2).'%' : '0%';
        $heji['marketReachRateBase'] =$heji['marketTaskBase']>0 ? bcmul(bcdiv($heji['achievementMoney'],$heji['marketTaskBase'],2),'100',2).'%' : '0%';
        $sum = [
            'list'=>[],
            'marketName'=>$heji['marketName'],
            'marketTask'=>$heji['marketTask'],
            'marketReachRate'=>$heji['marketReachRate'],
            'marketReach'=>$heji['marketReach'],
            'marketTaskBase'=>$heji['marketTaskBase'],
            'marketReachRateBase'=>$heji['marketReachRateBase'],

        ];
        array_push( $sum['list'],$heji);
        $data3['合计']=$sum;
//        array_push($data3,$sum);
        $data = [];
        foreach ($data3 as $value) {
            array_push($data, $value);
        }
        if(!empty($request['export']))
        {
            array_push($list,$heji);
            $data=$list;
        }
        return [

            'list' =>  $data,

            'timeReachRate' =>  (round(bcdiv($today,$days,4)*100,2)),

            'shopCount' =>  $count,

            'dataCount' =>$count

        ];

    }

    /**
     * 店铺任务导入模板
     *
     * @return string[]
     */
    public function getShopAchievementExcel()
    {
        $shop = Db::name('shop')->where('status','=',1)->column('market_id,shop_id,shop_name');
        foreach ($shop as $key =>$value)
        {
            $shop[$key]['shop_id']=$value['shop_id']." ";
        }
        $callName = ['market_id'=>"市场id",'shop_id'=>"门店id",'shop_name' => '店铺','one' =>'任务金额','two'=>'任务金额(基础)'];
        $downUrl =exportExcelData('任务导入模板',$callName,$shop,'xlsx',1);
        return [

            'url' => 'http://' . $_SERVER['HTTP_HOST'] . $downUrl,

        ];

    }

    /**

     * @author ran

     * @date 2022-03-09 10:46

     * mailbox 466180170@qq.com
	 * 转诊：门店退款方式是店转 取金额*系数  加上 转店ID等于大学路金额*系数；
     */

    public function referralMoney($shopId,$shop_type,$startTime,$endTime){
		//门店--转店ID 等于当前门店的ID
        $receive =Db::name('shop_refund_order')

            ->field('sum(pay_amount * coefficient) as pay_amount,id')

            ->where('referral_shop_id','=',$shopId)

            ->where('type','=',3)

            ->where('status','=',2)

            ->where('refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })->find();

		//退款单 店转金额 【判定疗程和非疗程
		$refund1 = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')

            ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','=','06')

            ->where('r.type','=',1)

            ->where('r.status','=',2)

            ->where('r.refund_type','<>','101.03')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            // ->find();

            ->column('r.pay_amount * r.coefficient as pay_amount','r.id');

		//退款单 是非店转的 店转金额
		$refund2 = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')

		    ->where('r.shop_id','=',$shopId)

		    ->where('g.refund_mode','<>','06')

		    ->where('r.type','=',1)

		    ->where('r.status','=',2)

			->where('r.combo','<>',3)

		    ->where('r.refund_type','<>','101.03')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    // ->find();

		    ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


		//门诊收款单 是非疗程的 转诊业绩
		$receiveMz =Db::name('shop_refund_order')

		    ->field('sum(pay_amount * coefficient) as pay_amount')

		    ->where('shop_id','=',$shopId)

			->where('is_treatment','=',2)

		    ->where('type','=',3)

			->where('referral_shop_id','>',0)

		    ->where('status','=',2)

		    ->where('refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })->find();

			//})->column('pay_amount * coefficient as pay_amount','id');
			//var_dump($receiveMz);
		//门诊 收款方式是店转 的 店转金额
		$refundMz = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')

            ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','=','06')

            ->where('r.type','=',3)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            // ->find();

            ->column('r.pay_amount * r.coefficient as pay_amount','r.id');

        $refund_sum = array_sum($refund1);
		$refund_sumT = array_sum($refund2);

        $refundMz_sum = array_sum($refundMz);

		if($shop_type==1){ //1是门诊 2是门店

			return round(bcsub(0,$receiveMz['pay_amount'],2)+$refundMz_sum+bcsub(0,$refund_sum,2)+bcsub(0,$refund_sumT,2),2);
			//return round(bcsub(0,$receiveMz['pay_amount'],2)+$refundMz_sum+bcsub(0,$refund_sum,2),2);

		}else{

			//return round(bcsub($receive['pay_amount'],$refund_sum,2)+bcsub(0,$refund_sumT,2),2);
			return round((bcsub($receive['pay_amount'],$refund_sum,2)+$refundMz_sum),2);

		}

    }


	/**

	 * @author ran

	 * @date 2022-06-23 14:46

	 * mailbox 466180170@qq.com
	 * 调整数据报表中的业绩金额计算
	 *  定义实收款：收款单 收款类型是收款，且收款方式 不含店转的本金合计 减去 退款单 里面 退款类型是 退款 ，退款方式 不含店转的金额合计；
	 */

	public function amountMoneyAll($shopId,$startTime,$endTime){

		//收款单 收款类型是 收款 且不含收款方式不是店转的
		$receive = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')

            ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','<>','06')

            ->where('r.type','=',3)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            // ->find();

            ->column('r.pay_amount as pay_amount','r.id');
			//->column('r.pay_amount * r.coefficient as pay_amount','r.id');

		//var_dump($receive);
		//退款单
		$refund = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')

            ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','<>','06')

            ->where('r.type','=',1)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            // ->find();

            //->column('r.pay_amount * r.coefficient as pay_amount','r.id');
			->column('r.pay_amount  as pay_amount','r.id');

		// return round($receive['pay_amount'] -$refund['pay_amount'],2);

        $receive_sum = array_sum($receive);

        $refund_sum = array_sum($refund);

        return bcsub($receive_sum,$refund_sum,2);

	}
	/*
	 * @ 疤痕业绩和项目业绩的 计算 逻辑----川渝市场的 疤痕和项目业绩计算
	 *
	 * @ 门店疤痕/项目业绩计算 ：收款单（不含店转）的疤痕/项目 实收金额 【减去】 退款单（不含店转）的疤痕/项目 实收金额
	 *                       【加上】  门诊转到门店的 疤痕/项目 实收金额 【减去】 退款单是店转的 疤痕/项目金额 【加上】 收款单是店转的疤痕/项目金额；
	 *
	 * @ 门珍疤痕/项目业绩计算 ：收款单（不含店转）的疤痕/项目 实收金额 【减去】 退款单（不含店转）的疤痕/项目 实收金额
	 *                       【加上】  非疗程不含店转的 疤痕/项目 实收金额 【减去】 退款单是店转的 疤痕/项目金额 【加上】 收款单是店转的疤痕/项目金额；
	 */
	public function sumShopPayMoneyNewMZ($scene,$shopId,$shop_type,$startTime,$endTime){
		switch ($scene) {
			case 'Bh':

		        $where['r.business_type']=1;
				break;

		    case 'XM':

		        $where['r.business_type']=2;
				break;

		    default:

		        break;

		}

		//收款单 收款类型是 收款 且不含收款方式不是店转的
		$receive = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')
		    ->where($where)
		    ->where('r.shop_id','=',$shopId)

		    ->where('g.refund_mode','<>','06')

		    ->where('r.type','=',3)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    // ->find();

		    ->column('r.pay_amount as pay_amount','r.id');
			//->column('r.pay_amount * r.coefficient as pay_amount','r.id');

		//var_dump($receive);
		//退款单
		$refund = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')

		    ->where('r.shop_id','=',$shopId)

		    ->where('g.refund_mode','<>','06')

		    ->where('r.type','=',1)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    // ->find();

		    //->column('r.pay_amount * r.coefficient as pay_amount','r.id');
			->column('r.pay_amount  as pay_amount','r.id');

		// return round($receive['pay_amount'] -$refund['pay_amount'],2);

		$receive_sum = array_sum($receive);

		$refund_sum = array_sum($refund);

		return bcsub($receive_sum,$refund_sum,2);
	}


	/*
	 * @ 疤痕业绩和项目业绩的 计算 逻辑
	 *
	 * @ 门店疤痕/项目业绩计算 ：收款单（不含店转）的疤痕/项目 实收金额 【减去】 退款单（不含店转）的疤痕/项目 实收金额
  	 *                       【加上】  门诊转到门店的 疤痕/项目 实收金额 【减去】 退款单是店转的 疤痕/项目金额 【加上】 收款单是店转的疤痕/项目金额；
	 *
	 * @ 门珍疤痕/项目业绩计算 ：收款单（不含店转）的疤痕/项目 实收金额 【减去】 退款单（不含店转）的疤痕/项目 实收金额
  	 *                       【加上】  非疗程不含店转的 疤痕/项目 实收金额 【减去】 退款单是店转的 疤痕/项目金额 【加上】 收款单是店转的疤痕/项目金额；
	 */
	public function sumShopPayMoneyNew($scene,$shopId,$shop_type,$startTime,$endTime){
		//$where =['shop_id'=> $shopId,'type'=>3];
		switch ($scene) {
			case 'Bh':

		        $where['business_type']=1;
				$wheret['r.business_type']=1;
				break;

		    case 'XM':

		        $where['business_type']=2;
				$wheret['r.business_type']=2;
				break;

		    default:

		        break;

		}
		//收款单中的疤痕业绩 不含店转的业绩--01
		$receive = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            //->field('sum(g.pay_price * r.coefficient) as pay_amount')
			->field('sum(g.pay_price) as pay_amount')
            ->where('r.shop_id','=',$shopId)

            ->where($wheret)

            ->where('g.refund_mode','<>','06')

            ->where('r.type','=',3)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            ->find();

            // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


		//退款单中的疤痕业绩	--不含店转的业绩  --02
		$refund = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            //->field('sum(g.pay_price * r.coefficient) as pay_amount')
			->field('sum(g.pay_price) as pay_amount')
            ->where('r.shop_id','=',$shopId)

            ->where($wheret)

            ->where('g.refund_mode','<>','06')

            ->where('r.type','=',1)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            ->find();

            // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


		//门诊转店到 门店的 通过门店的归属ID 查询	--收款单 --03
		$receive_zd =Db::name('shop_refund_order')

		    ->field('sum(pay_amount * coefficient) as pay_amount,id')

			->where($where)

		    ->where('referral_shop_id','=',$shopId)

		    ->where('type','=',3)

		    ->where('status','=',2)

		    ->where('refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })->find();


		//退款单是店转的 疤痕/项目业绩查询  --04
		$refund_dz = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            ->field('sum(g.pay_price * r.coefficient) as pay_amount')

            ->where($wheret)

            ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','=','06')

            ->where('r.type','=',1)

            ->where('r.status','=',2)

            ->where('r.refund_type','<>','101.03')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            ->find();

            // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


		//收款单是店转的 疤痕/项目业绩---05
		$receive_dz = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            ->field('sum(g.pay_price * r.coefficient) as pay_amount')

            ->where('r.shop_id','=',$shopId)

            ->where($wheret)

            ->where('g.refund_mode','=','06')

            ->where('r.type','=',3)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            ->find();

            // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


		//门诊收款单 是非疗程的 疤痕/项目业绩  --06
		$receive_mz =Db::name('shop_refund_order')

		    ->field('sum(pay_amount * coefficient) as pay_amount')

			->where($where)

		    ->where('shop_id','=',$shopId)

			->where('is_treatment','=',2)

		    ->where('type','=',3)

			->where('referral_shop_id','>',0)

		    ->where('status','=',2)

		    ->where('refund_type','<>','101.03')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })->find();

		if($shop_type==1){ //1是门诊 2是门店
			//return round($receive['pay_amount']-$refund['pay_amount'] +$receive_dz['pay_amount']+bcsub(0,$receive_mz['pay_amount'],2)+bcsub(0,$refund_dz['pay_amount']),2);
			return round(($receive['pay_amount']-$refund['pay_amount'] +$receive_dz['pay_amount']-$receive_mz['pay_amount']-$refund_dz['pay_amount']),2);
		}else{
			//实收金额 - 退款金额 + 门诊收钱分给店面的一半金额
			return round(($receive['pay_amount']-$refund['pay_amount'] +$receive_zd['pay_amount']+$receive_dz['pay_amount']-$refund_dz['pay_amount']),2);
		}
	}

     /**

     * @param $scene

     * @param $shopId

     * @param $startTime

     * @param $endTime

     * @author ran

     * @date 2022-01-18 17:26

     * mailbox 466180170@qq.com

     */

    public function shopAchievementStatisticsCollection($scene,$shopId,$startTime,$endTime){

        return round($this->sumShopPayMoney($scene,$shopId,$startTime,$endTime)-$this->sumShopRefundMoney($scene,$shopId,$startTime,$endTime),2);

    }

    /**

     * 收款单金额

     * @param $scene

     * @param $shopId

     * @param $startTime

     * @param $endTime

     * @author ran

     * @date 2022-01-18 17:10

     * mailbox 466180170@qq.com

     */

    public function sumShopPayMoney($scene,$shopId,$startTime,$endTime){

        $where =['shop_id'=> $shopId,'type'=>3];
		switch ($scene) {

            case 'all':

                $where=['shop_id'=> $shopId,'type'=>3];
				break;

            case 'Bh':

                $where['business_type']=1;
				 break;

            case 'XM':

                $where['business_type']=2;
				break;

            default:

                break;

        }

       //收款单

        $receive = Db::name('shop_refund_order')

            ->field('sum(pay_amount * coefficient) as pay_amount')

            ->where($where)

            ->where('status','=',2)

            ->where('refund_type','<>','101.03')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })->find();

            return $receive['pay_amount'];

    }



    /**

     * 退款单金额

     * @param $scene

     * @param $shopId

     * @param $startTime

     * @param $endTime

     * @author ran

     * @date 2022-01-18 17:05

     * mailbox 466180170@qq.com

     */

    public function sumShopRefundMoney($scene,$shopId,$startTime,$endTime)

    {

        $where =['shop_id'=> $shopId,'type'=>1];

        switch ($scene) {

            case 'Bh':

                $where['business_type']=1;

                break;

            case 'XM':

                $where['business_type']=2;

                break;

            default:

                break;

        }

        $refund = Db::name('shop_refund_order')

            ->field('sum(pay_amount * coefficient) as pay_amount')

            ->where($where)

            ->where('refund_type','<>','101.03')

            ->where('refund_type','<>','101.01')

            ->where('status','<>',3)

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })->find();

        return $refund['pay_amount'];

    }



    /**

     * @author ran

     * @date 2021-11-25 16:02

     * mailbox 466180170@qq.com

     */

    public function getAdminShopStatistics($shopIds,int $page, int $limit,$request)

    {
		// echo "<pre>";
		// print_r($request);
		// echo "</pre>";

		$model = new ReserveandLost();

		$today = date('Y-m-d',time());

		//var_dump($request);
        $start_time_int = $request['start_time'] ?? date('Y-m-d');
        $end_time_int = $request['end_time'] ?? date('Y-m-d 23:59:59');
        $start_time = strtotime($start_time_int);

		$old_start_time=strtotime(date("Y-m-01 00:00:00",strtotime("-4 month",$start_time)));// 新单成交  开始时间
		$old_end_time=strtotime(date('Y-m-01', $old_start_time) . ' 1 month -1 day'. ' 23:59:59');//新单成交 成交结束时间

		$tj_start_time=strtotime(date("Y-m-01 00:00:00",strtotime("-3 month",$start_time)));// 查询开始时间
		$tj_end_time=strtotime(date('Y-m-01', $tj_start_time) . ' 1 month -1 day'. ' 23:59:59');//新单成交 成交结束时间
		$end_time = strtotime($end_time_int)+86399;  //查询结束时间

        $type = $request['type']??"";

        $where = [];
        if(!empty($type))
        {
            array_push($where,['type','=',$type]);
        }
        array_push($where,['status','=',1]);
        array_push($where,['shop_id','<>',74076159037951]);



        $field = ['shop_id as shopId', 'shop_name as shopName','market_name as marketName','area','bed_num as bedNum','shop_type'];
        $connect = Db::name('shop')->field($field)
            //->where(['type'=> 1,'status'=>1,'shop_type'=>2])
//			->where(['status'=>1])
//			->where('shop_id','<>',74076159037951)
            ->where($where)
            ->when($shopIds ?? [], function ($query) use ($shopIds) {
                return $query->whereIn('shop_id', $shopIds);
            });
        //预存结余
        $balanceList = Db::name('customer_balance_tj')
            ->field('sum(money) as money,complimentary_money as complimentary,shop_id')
            ->where('time','=',date('Ymd',$start_time))
            ->group('shop_id')->select()->toArray();
        $balanceBindList=array_column($balanceList,null,'shop_id');
        //预存结余
        $balanceList = Db::name('customer_balance_tj')
            ->field('sum(money) as money,complimentary_money as complimentary,shop_id')
            ->where('time','=',date('Ymd',$start_time))
            ->group('shop_id')->select()->toArray();
        $balanceBindList=array_column($balanceList,null,'shop_id');
        //本月消耗 //本月消耗 =销售出库单金额合计-销售退货单金额合计
        //预查询出库单金额合计
		/* var_dump($start_time);
		var_dump($end_time); */
        $chukuOrder = Db::name('shop_order')
            ->where('status','<>',4)
            ->where('deal_time','>=',$start_time)
            ->where('deal_time','<=',$end_time)
            ->group('shop_id')
            ->column('sum(order_amount) as pay_amount,shop_id','shop_id');
        //预查询销售退货单金额合计
        $refundOrder = Db::name('shop_refund_order')
            ->where('type','=',2)
            ->where('status','<>',3)
            ->where('deal_time','>=',$start_time)
            ->where('deal_time','<=',$end_time)
            ->group('shop_id')
            ->column('sum(total_amount) as pay_amount,shop_id','shop_id');
        //当前本期实收 =  当月该门店收款单金额合计-当月该门店退款单金额合计
        //收款单
        $collectionOrder = Db::name('shop_refund_order')
            ->where('status','<>',3)
            ->where('type',3)
            ->where('refund_type','<>','101.03')
            ->where('deal_time','>=',$start_time)
            ->where('deal_time','<=',$end_time)
            ->group('shop_id')
            ->column('sum(pay_amount) as pay_amount,shop_id','shop_id');
        //退款单
        $refundcollectionOrder = Db::name('shop_refund_order')
            ->where('status','<>',3)
            ->where('type',1)
            ->where('refund_type','<>','101.03')
            ->where('deal_time','>=',$start_time)
            ->where('deal_time','<=',$end_time)
            ->group('shop_id')
            ->column('sum(pay_amount) as pay_amount,shop_id','shop_id');
        //上期末预存结余 =3月31号 该门店所有的预存金额合计
        $upperTerm = Db::name('customer_balance_tj')
            ->field('sum(money) as money,complimentary_money as complimentary,shop_id')
            ->where('time','=',date('Ymd',strtotime(date('Y-m-t', strtotime('-1 month')))))
            ->group('shop_id')->select()->toArray();
        $upperTerm=array_column($upperTerm,null,'shop_id');
        //成交人数--tj
        $dealList =Db::name('customer')
            ->where('cj_time','>=',$old_start_time)
            ->where('cj_time','<=',$old_end_time)
            ->where('cj_money','>',0)
            ->group('shop_id')
            ->column('count(id) as count,shop_id','shop_id');
        //2月项目新成交人数在 business_type 1是疤痕  2是项目
        $dealRealpro = Db::name('customer')
            ->alias('b')
            ->where('b.cj_time','>',$tj_start_time)
            ->where('b.cj_time','<',$end_time_int)
            ->where('b.cj_money','>',0)
            ->leftjoin('shop_refund_order sp','b.cj_order_id = sp.id')
            ->where('sp.business_type','=',2)
            ->where('sp.type','=',3)
            ->group('shop_id')
            ->column('count(b.id) as count,b.shop_id','b.shop_id');


		//var_dump('路过辞职');
        //月直接 有再次消费 其成交类型是疤痕的 business_type 1是疤痕  2是项目
        $dealRealbahen = Db::name('customer')
            ->alias('b')
            ->where('b.cj_time','>=','1640970061')//2022.01.01
            ->where('b.cj_time','<=','1643644799') //2022.01.31
            ->where('b.cj_money','>',0)
            ->leftjoin('shop_refund_order sp','b.cj_order_id = sp.id')
            ->where('sp.business_type','=',1)
            ->where('sp.type','=',3)
            ->group('shop_id')
            ->column('count(b.id) as count,b.shop_id','b.shop_id');

        $count =$connect-> count();
        //$list =$connect->page($page, $limit)->select();
		$list =$connect->select();

        $list =empty($list) ? [] : $list->toArray();
		//调取 项目普及率

		// echo "<pre>";
		// print_r($list);
		// echo "</pre>";
		// exit;

		$cj_type = $request['cj_type'] ?? 0;

		//var_dump($list);
        foreach ($list as $key => $value) {
            $money =$balanceBindList[$value['shopId']]['money']??0;
            $complimentary =$balanceBindList[$value['shopId']]['complimentary']??0;
            //销售出库单金额合计
            $chukuOrderMoney =$chukuOrder[$value['shopId']]['pay_amount']??0;
            //销售退货单金额合计
            $refundOrderMoney =$refundOrder[$value['shopId']]['pay_amount']??0;
            $list[$key]['money'] = bcadd($money,$complimentary,2);
            $list[$key]['referralCount'] = 0;
            $list[$key]['referralMoney'] = 0.00;
            //本月消耗 =销售出库单金额合计-销售退货单金额合计
            $list[$key]['consumeMoney'] = bcsub($chukuOrderMoney,$refundOrderMoney,2);
            $m =$upperTerm[$value['shopId']]['money']??0;
            $c =$upperTerm[$value['shopId']]['complimentary']??0;
            //上期末预存结余
            $upperTermMoney =bcadd($m,$c,2);
            //当前本期实收 =  当月该门店收款单金额合计-当月该门店退款单金额合计
            $cm =$collectionOrder[$value['shopId']]['pay_amount']??0;
            $rm =$refundcollectionOrder[$value['shopId']]['pay_amount']??0;
            $receiptsMoney =bcsub($cm,$rm,2);
            $con =bcadd($upperTermMoney,$receiptsMoney,2)==0?1:bcadd($upperTermMoney,$receiptsMoney,2);
            //消耗占比 =本月消耗/（上期末预存结余+当前本期实收）
            $consumeRate =(round($list[$key]['consumeMoney']/$con,2)*100).'%';

			$list[$key]['consumeRate'] = $consumeRate;  //消耗占比
			//成交的疤痕顾客  business_type 1是疤痕
			$scarList = Db::name('customer')
			    ->alias('b')
			    ->where('b.cj_time','>=',$old_start_time)//2022.01.01
			    ->where('b.cj_time','<=',$old_end_time) //2022.01.31
			    ->where('b.cj_money','>',0)
			    ->leftjoin('shop_refund_order sp','b.cj_order_id = sp.id')
			    ->where('sp.business_type','in',[1,3])
			    ->where('sp.type','=',3)
				->where('sp.shop_id','=',$value['shopId'])
			    ->column('b.id,b.shop_id,b.cj_money,telephone');

			//var_dump(count($scarList));
			//查询疤痕二次消费

			/* echo  '<pre>';
			print_r($scarList); */


			$bahenNum =$this->redAdminProjectByShopId($scarList,$old_start_time,$old_end_time,$end_time);

			$xiangmNum =$this->redAdminXmByShopId($scarList,$old_start_time,$old_end_time,$end_time);

			$gxmanyiNum =$this->setGXmanyiCustomerShopList($scarList,$old_start_time,$old_end_time,$end_time);


			$list[$key]['developRate'] =count($scarList)>0 ? (bcdiv($bahenNum,count($scarList),4)*100).'%' :'0%';  //疤痘二次消费率
			$list[$key]['popularityRate'] =count($scarList)>0 ? (bcdiv($xiangmNum,count($scarList),4)*100).'%' :'0%'; //项目普及率
			$list[$key]['gongxiaomanyi'] =count($scarList)>0 ? (bcdiv($gxmanyiNum,count($scarList),4)*100).'%' :'0%'; //功效满意度

			// 保有流失计算
			$list[$key]['cj_customer'] = "——";
			$list[$key]['baoyou_customer'] = "——";
			$list[$key]['lost_customer'] = "——";
			$list[$key]['warn_customer'] = "——";
			$list[$key]['back_customer'] = "——";
			$list[$key]['tag_customer'] = "——";
			$list[$key]['rate_baoyou'] = "——";

			if($value['shop_type'] == '2'){

				$shopIds = [];

				array_push($shopIds,$value['shopId']);

				// 总成交顾客数
				$cj_customer = $model->cj_customer($shopIds,['cj_type' => $cj_type]);

				// echo "<pre>";
				// print_r($cj_customer);
				// echo "</pre>";

				$list[$key]['cj_customer'] = count($cj_customer);

				// 保有顾客数
				$baoyou_customer = $model->baoyou_customer($cj_customer,$today);

				$list[$key]['baoyou_customer'] = count($baoyou_customer);

				// 流失顾客数
				$lost_customer = $model->lost_customer($cj_customer,$today);

				$list[$key]['lost_customer'] = count($lost_customer);

				// 月初流失预警顾客
				// $warn_customer = $model->warning_customer('','','back',$shopIds,$request['start_time']);
				$warn_customer = $model->warning_customer('','','back',$shopIds,$start_time_int);

				$list[$key]['warn_customer'] = count($warn_customer);

				$over_time = strtotime($end_time_int) ?? time();

				// 预警回流顾客数
				// $back_customer = $model->back_customer($warn_customer,$request['start_time'],$over_time);
				$back_customer = $model->back_customer($warn_customer,$start_time_int,$over_time);

				$list[$key]['back_customer'] = count($back_customer);

				$list[$key]['rate_back'] = count($warn_customer)>0 ? (round(count($back_customer)/count($warn_customer),4)*100).'%' :'0%'; // 流失预警回流率

				// 标签顾客
				$tag_customer = $model->tag_customer($cj_customer);

				$list[$key]['tag_customer'] = count($tag_customer);

				$list[$key]['rate_baoyou'] = count($cj_customer)>0 ? (round(count($baoyou_customer)/count($cj_customer),4)*100).'%' :'0%'; // 成交保有率

			}


        }
        $data3= [];
        foreach ($list as $value)
        {
            if(empty($data3[$value['marketName']]))
            {
                $data3[$value['marketName']]['marketName']=$value['marketName'];
                $data3[$value['marketName']]['list']=[];
            }
            array_push($data3[$value['marketName']]['list'],$value);
        }

        $data              = [];

        $data = [];
        foreach ($data3 as $value) {
            array_push($data, $value);
        }
        if(!empty($request['export']))
        {
            $data=$list;
        }

        return [

            'list' =>  $data,

            'dataCount' => $count

        ];

    }

	/*
	@ 计算门店疤痕二次消费率
	*/

	public function redAdminProjectByShopId($scarList,$start_time,$end_time,$tj_end_time){
		$bahenNum = 0;
		foreach ($scarList as $k1 => $val) {
			$sumMoney = Db::name('customer')->where([
				['telephone','=',$val['telephone']],
				['status','=',1]
			])->group('telephone')->sum('cj_money');
			$customerIds = Db::name('customer')->where([
				['telephone','=',$val['telephone']],
				// ['status','=',1]
			])->column('id');
			//疤痕成交收款单合计
			$bahentwoSK =Db::name('shop_refund_order')
			    ->where('deal_time','>=',$start_time)
			    ->where('deal_time','<=',$tj_end_time)
			    // ->where('uid','=',$val['id'])
				->where('uid','in',$customerIds)
				->where('type','=',3)
                ->where('status','=',2)
				->where('business_type','in',[1,3])
				->where('refund_type','<>',101.03)
			    ->column('sum(pay_amount) as count,shop_id');
			//疤痕成交退款单合计
			$bahentwoTK =Db::name('shop_refund_order')
			    ->where('deal_time','>=',$start_time)
			    ->where('deal_time','<=',$tj_end_time)
			    // ->where('uid','=',$val['id'])
				->where('uid','in',$customerIds)
				->where('type','=',1)
                ->where('status','=',2)
				->where('business_type','in',[1,3])
				->where('refund_type','<>',101.03)
			    ->column('sum(pay_amount) as count,shop_id');
			$totalamountwo = bcsub($bahentwoSK[0]['count'], $bahentwoTK[0]['count'],2);
			$totalamount = bcsub($totalamountwo, $sumMoney,2);

			$customer_name = Db::name('customer')->where([
				['telephone','=',$val['telephone']],
				// ['status','=',1]
			])->column('customer_name');

			// echo "<pre>";
			// print_r($customer_name);
			// echo "</pre>";
			// echo $totalamount;
			// echo "<br/>";
			// echo "-------------<br/>";


			if($totalamount >= 500){
				$bahenNum++;
			}
		}
		return 	$bahenNum;
	}

	public function redAdminXmByShopId($scarList,$start_time,$end_time,$tj_end_time){

		$xiangmNum = 0;
		$xiangmBqNum = 0;
		foreach ($scarList as $k1 => $val) {
			// $sumMoney = Db::name('customer')->where([
			// 	['telephone','=',$val['telephone']],
			// 	['status','=',1]
			// ])->group('telephone')->sum('cj_money');
			$customerIds = Db::name('customer')->where([
				['telephone','=',$val['telephone']]
			])->column('id');
			//项目普及率的计算公式
			$xiangmtwoSK =Db::name('shop_refund_order')
				->where('deal_time','>=',$start_time)
				->where('deal_time','<=',$tj_end_time)
				// ->where('uid','=',$val['id'])
				->where('uid','in',$customerIds)
				->where('type','=',3)
                ->where('status','=',2)
				->where('business_type','in',[2,4])
				->where('refund_type','<>',101.03)
				->column('sum(pay_amount) as count,consignee,shop_id');

			$xiangmtwoTK =Db::name('shop_refund_order')
				->where('deal_time','>=',$start_time)
				->where('deal_time','<=',$tj_end_time)
				// ->where('uid','=',$val['id'])
				->where('uid','in',$customerIds)
				->where('type','=',1)
                ->where('status','=',2)
				->where('business_type','in',[2,4])
				->where('refund_type','<>',101.03)
				->column('sum(pay_amount) as count,shop_id');
			$totalamountXM = bcsub($xiangmtwoSK[0]['count'], $xiangmtwoTK[0]['count'],2);
			//标记 项目普及率标签

			if($totalamountXM >= '500'){
				//echo '进入---11111';echo '<br/>';
				$xiangmNum++;
			}else{
				$xiangmBQ =Db::name('customer')
					// ->where('id','=',$val['id'])
					->where('id','in',$customerIds)
					->where('member_label','like','%617%')
					->column('id,shop_id');

				if(!empty($xiangmBQ)){
					$xiangmBqNum++;
				}
			}
		}
		return 	round(bcadd($xiangmNum,$xiangmBqNum,1));
	}

	/* 计算 功效满意度 */
	/*
	* @ 功效满意度  gongxiaomanyi
	* @ 是否满足 成交客户再次消费疤痕金额大于等于500
	* @ 是否满足 客户转介绍并成交新单 金额>=500
	* @ 是否满足在规定时间内申请优秀和满意案例
	* @ 三者满足一个即为满意个数
	*/


	public function setGXmanyiCustomerShopList($scarList,$start_time,$end_time,$tj_end_time){

		// echo '开始时间--'.$start_time;echo '<br/>';
		// echo '结束时间--'.$end_time;echo '<br/>';
		// echo '统计结束时间--'.$tj_end_time;echo '<br/>';exit;

		// echo '<pre>';
		// print_r($scarList);exit;

		$gxmanyiNum = 0;

		$gxbhAmount = '';
		$cuetomerCase = '';
		$cuetomerTurn = '';

		foreach ($scarList as $k1 => $val) {

            $customerIds = Db::name('customer')->where([
                ['telephone','=',$val['telephone']],
                // ['status','=',1]
            ])->column('id');
            $sumMoney = Db::name('customer')->where([
                ['telephone','=',$val['telephone']],
                ['status','=',1]
            ])->group('telephone')->sum('cj_money');
			// 是否满足 成交客户再次消费疤痕金额大于等于500

			//疤痕成交收款单合计
			$bahentwoSK =Db::name('shop_refund_order')
			    ->where('deal_time','>=',$start_time)
			    ->where('deal_time','<=',$tj_end_time)
//			    ->where('uid','=',$val['id'])
                ->where('uid','in',$customerIds)

				->where('type','=',3)
				->where('status','=',2)
				->where('business_type','in',[1,3])
				->where('refund_type','<>',101.03)
			    ->column('sum(pay_amount) as count,shop_id');
			//疤痕成交退款单合计
			$bahentwoTK =Db::name('shop_refund_order')
			    ->where('deal_time','>=',$start_time)
			    ->where('deal_time','<=',$tj_end_time)
//			    ->where('uid','=',$val['id'])
                ->where('uid','in',$customerIds)

				->where('type','=',1)
				->where('status','=',2)
				->where('business_type','in',[1,3])
				->where('refund_type','<>',101.03)
			    ->column('sum(pay_amount) as count,shop_id');
			$totalamountwo = bcsub($bahentwoSK[0]['count'], $bahentwoTK[0]['count'],2);
			$totalamount = bcsub($totalamountwo, $sumMoney,2);
			if($totalamount >= 500){
				$gxbhAmount = 'Y';
			}else{
				$gxbhAmount = 'N';
			}


			//是否满足 客户转介绍并成交新单 金额>=500
			$turnlist_t =Db::name('customer')
			   ->where('turn_cjtime','>=',$start_time)
			   ->where('turn_cjtime','<=',$tj_end_time)
			   ->where('id','=',$val['id'])
			   ->where('turn_customerid','>',0)
			   ->column('id');


			if(empty($turnlist_t)){
				$cuetomerTurn = 'N';

			}else{
				$cuetomerTurn = 'Y';
			}


			//是否满足在规定时间内申请优秀和满意案例
			$caseArray =[2,3];
			//是否满足在规定时间内申请优秀和满意案例
			$caselist_t =Db::name('case')
			   ->where('tg_excellent_time','>=',$start_time)
			   ->where('tg_excellent_time','<=',$tj_end_time)
			   ->where('customer_id','=',$val['id'])
			   ->where('selection_results','in',$caseArray)
			   ->column('customer_id as id');

			/* echo '<pre>';
			print_r($caselist_t);
			 */
			if(empty($caselist_t)){

				$cuetomerCase = 'N';
			}else{
				$cuetomerCase = 'Y';

			}

			if($cuetomerCase == 'Y' || $cuetomerTurn == 'Y' || $gxbhAmount =='Y'){
				$gxmanyiNum++;
			}

		}
		return $gxmanyiNum;
	}



    /*
	#  @ 项目普及率 疤痕二次开发率 和功效满意度的 二级详情页面
	*/
    public function readAdminCustomerByShopId($shopId,$type,$page,$limit,$request){

        $start_time_int = $request['start_time'] ?? date('Y-m-d');
        $end_time_int = $request['end_time'] ?? date('Y-m-d 11:59:59');
        $start_time = strtotime($start_time_int);
        //$end_time = strtotime($end_time_int);
		// 1月成交的新单疤痕顾客在 1、2、3、4月份有再次消费疤痕或者项目的 数据统计
		// $type = 2是项目 1是疤痕 3是 功效
		$tj_start_time=strtotime(date("Y-m-01 00:00:00",strtotime("-4 month",$start_time)));// 查询开始时间
		$tj_end_time=strtotime(date('Y-m-01', $tj_start_time) . ' 1 month -1 day'. ' 23:59:59');//新单成交 成交结束时间
		$end_time = strtotime($end_time_int)+86399;  //查询结束时间
		$list = [];

		// echo  '查询开始时间'.$tj_start_time;echo '<br/>';
		// echo  '成交结束时间'.$tj_end_time;echo '<br/>';
		// echo  '查询结束时间'.$end_time;echo '<br/>';exit;
		$businessTypeY = Db::name('customer_balance_category')->column('name','id');
		//var_dump($type);//exit;
		if($type != 3){ //计算 疤痕二次开发率 和项目普及率

			$scarList = Db::name('customer')
				//->field('b.customer_name,b.telephone,b.cj_money,sp.business_type,sp.shop_name,sp.uid')
				->alias('b')
				->where('b.cj_time','>=',$tj_start_time)//2022.01.01
				->where('b.cj_time','<=',$tj_end_time) //2022.01.31
				->where('b.cj_money','>',0)
				->leftjoin('shop_refund_order sp','b.cj_order_id = sp.id')
				->where('sp.business_type','in',[1,3])
				->where('sp.status','=',2)
				->where('sp.type','=',3)
				->where('sp.shop_id','=',$shopId)
				->column('b.id,b.shop_id,b.customer_name,b.telephone,b.cj_time,b.cj_money,sp.business_type,sp.shop_name,sp.uid');

			$count =count($scarList);
			$list = [];
			foreach ($scarList as $key => $value) {

				$list[$key]['shop_name'] = $value['shop_name'];
				$list[$key]['customer_name'] = $value['customer_name'];
				$list[$key]['telephone'] = $value['telephone'];
				$list[$key]['cj_amounty'] = $value['cj_money'];
				$list[$key]['cj_timet'] = date('Y-m-d', $value['cj_time']);
				$list[$key]['business_type'] = $businessTypeY[$value['business_type']];

				$customerIds = Db::name('customer')->where([
					['telephone','=',$value['telephone']]
				])->column('id');


				$bahentwoSK =Db::name('shop_refund_order')
					->where('deal_time','>=',$tj_start_time)
					->where('deal_time','<=',$end_time)
					// ->where('uid','=',$value['id'])
					->where('uid','in',$customerIds)
					->where('type','=',3)
					->where('status','=',2)
					->where('business_type','in',[1,3])
					->where('refund_type','<>',101.03)
					->column('sum(pay_amount) as count,shop_id');
				//var_dump($bahentwoSK);
				$bahentwoTK =Db::name('shop_refund_order')
					->where('deal_time','>=',$tj_start_time)
					->where('deal_time','<=',$end_time)
					// ->where('uid','=',$value['id'])
					->where('uid','in',$customerIds)
					->where('type','=',1)
					->where('status','=',2)
					->where('business_type','in',[1,3])
					->where('refund_type','<>',101.03)
					->column('sum(pay_amount) as count,shop_id');


				$totalamountSK = bcsub($bahentwoSK[0]['count'], $bahentwoTK[0]['count'],2);
				$totalamount = bcsub($totalamountSK, $value['cj_money'],2);

				// echo "姓名：".$value['customer_name'];
				// echo "<br/>";
				// echo $totalamount;
				// echo "<br/>";
				// echo "-------------<br/>";

				if($type==1){
					if($totalamount >= 500){
						$list[$key]['is_second'] = 2;
					}else{
						$list[$key]['is_second'] = 1;
					}
				}

				//项目普及率的计算公式
				$xiangmtwoSK =Db::name('shop_refund_order')
					->where('deal_time','>=',$tj_start_time)
					->where('deal_time','<=',$end_time)
					// ->where('uid','=',$value['id'])
					->where('uid','in',$customerIds)
					->where('type','=',3)
					->where('status','=',2)
					->where('business_type','in',[2,4])
					->where('refund_type','<>',101.03)
					->column('sum(pay_amount) as count,shop_id');
				//var_dump($bahentwoSK);
				$xiangmtwoTK =Db::name('shop_refund_order')
					->where('deal_time','>=',$tj_start_time)
					->where('deal_time','<=',$end_time)
					// ->where('uid','=',$value['id'])
					->where('uid','in',$customerIds)
					->where('type','=',1)
					->where('status','=',2)
					->where('business_type','in',[2,4])
					->where('refund_type','<>',101.03)
					->column('sum(pay_amount) as count,shop_id');
				$totalamountXM = bcsub($xiangmtwoSK[0]['count'], $xiangmtwoTK[0]['count'],2);

				if($type==2){
					if($totalamountXM >= 500){
						$list[$key]['is_second'] = 2;
					}else{
						$xiangmBQ =Db::name('customer')
							->where('id','=',$value['id'])
							->where('member_label','like','%617%')
							->column('id,shop_id');
						if(!empty($xiangmBQ)){
							$list[$key]['is_second'] = 2;
						}else{
							$list[$key]['is_second'] = 1;
						}

					}
				}
			}
		}else{ //计算 功效满意
			$order_cj_nowid =Db::name('customer')->alias('b')
			   ->where('b.cj_time','>=',$tj_start_time)
			   ->where('b.cj_time','<=',$tj_end_time)
			//    ->where('b.shop_id','=',$shopId)
			   ->where('b.cj_money','>',0)
			   ->leftjoin('shop_refund_order sp','b.cj_order_id = sp.id')
			   ->where('sp.business_type','in',[1,3])
			   ->where('sp.type','=',3)
			   ->where('sp.status','=',2)
			   ->where('sp.shop_id','=',$shopId)
			   ->column('b.id,b.shop_id,b.cj_money,b.customer_name,b.telephone,b.cj_time,sp.business_type');
			$count =count($order_cj_nowid);
			if(empty($order_cj_nowid)){


			}else{

				foreach ($order_cj_nowid as $k2 => $vall) {
					$caseArray =[2,3];
					//是否满足在规定时间内申请优秀和满意案例
					$caselist_t =Db::name('case')
					   ->where('tg_excellent_time','>=',$tj_start_time)
					   ->where('tg_excellent_time','<=',$end_time)
					   ->where('customer_id','=',$vall['id'])
					   ->where('selection_results','in',$caseArray)
					   ->column('customer_id as id');

					// echo $vall['id'].'是否规定时间申请案例';echo '<br/>';
					// echo '<pre>';
					// print_r($caselist_t);

					$where = [];
					array_push($where,['telephone','=', $vall['telephone'] ]);
					$customerList = Db::name('customer')->where($where)->column('id');
					// echo '<pre>';
					// print_r($customerList);

					//疤痕二次消费率
					$bahentwoSK =Db::name('shop_refund_order')
					    ->where('deal_time','>=',$tj_start_time)
					    ->where('deal_time','<=',$end_time)
					    //->where('uid','=',$vall['id'])
						->where('uid','in',$customerList)

						->where('type','=',3)
						->where('status','=',2)
						->where('business_type','in',[1,3])
						->where('refund_type','<>',101.03)
					    ->column('sum(pay_amount) as count,shop_id');
					//var_dump($bahentwoSK);
					$bahentwoTK =Db::name('shop_refund_order')
					    ->where('deal_time','>=',$tj_start_time)
					    ->where('deal_time','<=',$end_time)
					    ->where('uid','=',$vall['id'])
						->where('type','=',1)
						->where('status','=',2)
						->where('business_type','in',[1,3])
						->where('refund_type','<>',101.03)
					    ->column('sum(pay_amount) as count,shop_id');

					$bahenAmountSK = bcsub($bahentwoSK[0]['count'], $bahentwoTK[0]['count'],2);
					$bahenAmount = bcsub($bahenAmountSK, $vall['cj_money'],2);
					// var_dump('疤痕金额----'.$bahenAmount);
					// echo $vall['id'].'----'.'疤痕二次消耗金额----'.$bahenAmount;echo '<br/>';

					//客户是否转介绍并且成交新单
					$turnlist_t =Db::name('customer')
					   ->where('turn_cjtime','>=',$tj_start_time)
					   ->where('turn_cjtime','<=',$end_time)
					   ->where('id','=',$vall['id'])
					   ->where('turn_customerid','>',0)
					   ->column('id');

					// echo $vall['id'].'是否转介绍成交新单';echo '<br/>';
					// echo '<pre>';
					// print_r($turnlist_t);

					if(empty($caselist_t) && empty($turnlist_t) && $bahenAmount< 500){
						$list[$k2]['is_second'] = 1;
					}else{
						$list[$k2]['is_second'] = 2;
						//$gxmyd++;
					}

					$shopList = Db::name('shop')->where('shop_id','=',$shopId)->column('shop_name', 'shop_id');


					$list[$k2]['shop_name'] = $shopList[$vall['shop_id']] ?? '';
					$list[$k2]['customer_name'] = $vall['customer_name'];
					$list[$k2]['telephone'] = $vall['telephone'];
					$list[$k2]['cj_amounty'] = $vall['cj_money'];
					$list[$k2]['cj_timet'] = date('Y-m-d', $vall['cj_time']);
					$list[$k2]['business_type'] = $businessTypeY[$vall['business_type']];
				}
			}
		}

		$listSecond = array_column($list,'is_second');
		array_multisort($listSecond,SORT_ASC,$list);


        return [
            'list' =>  $list,
            'dataCount' => $count
        ];
    }



    /**

     * 根据用户信息获取角色数据权限公共店铺集合

     * @param string $scene 场景 目前支持市场一种场景

     * @param int $userId 用户ID

     * @param int $type 1、自身门店集合 2、自身门店+关联门店集合

     * @return array

     * @author ran

     * @date 2021-11-05 15:33

     * mailbox 466180170@qq.com

     */

    public function getCommonShopIdsCollect(string $scene, int $userId, int $type = 1): array

    {

        $accessModel = new Access();

        $dataAuth = $accessModel->getCommonUserDataAuth($userId);

        $shopIds = [];

        switch ($scene) {

            case 'market':

                $shop = $this->where('market_id', $dataAuth['market'])->find();

                switch ($type) {

                    case 1:

                        $shopIds[] = $shop['shopId'];

                        break;

                    case 2:

                        $shopIds = array_merge($shop['relationShop'], [$shop['shopId']]);

                        break;

                }

                break;

            default:

                break;

        }

        return $shopIds;

    }



    public function shopHandel(){

        $user= new UserModel();

        $arr =$user->where('type',2)->select()->toArray();

        $accessModel = new Access();

        foreach($arr as $value){

            $data =[

                'user_id'=>$value['id'],

                'group_id'=>2,

             ];

            $accessModel->insert( $data);

        }

    }


	public function readAdminShopAmountList($shopId,$type,$page,$limit,$request){

		$shopList = Db::name('shop')->where('shop_id', '=', $shopId)->column('shop_type,market_id');
		$shopType = $shopList[0]['shop_type'];
        $marketId = $shopList[0]['market_id'];

		$refundType[3]['101.02'] ='收款';
		$refundType[1]['101.01'] ='店面转诊';
		$refundType[1]['101.02'] ='退款';

		$typeArray  = ['3' => '收款单', '1' => '退款单'];
		$orderTypeArray  = ['1' => '新单', '2' => '补单'];
		$businessTypeArray  = ['1' => '疤痕', '2' => '项目', '3' => '青春痘', '4' => '护肤品'];

		$startTime = strtotime($request['start_time']);
		$endTime = strtotime($request['end_time'])+86399;

		//实收款列表
		if($type==1){

			$listAmount =$this->setAmountShopListArray($shopId,$startTime,$endTime);
			//$clientInfo = Db::name('customer')->column('id','telephone');
		}

        // 转诊
		if($type==2){

			$listAmount =$this->setZhuanZhenShopListArray($shopId,$shopType,$startTime,$endTime);
			//$clientInfo = Db::name('customer')->column('id','telephone');
		}

		if($type>=3){ //疤痕项目业绩

            if($marketId == 8 || $marketId == 9 || $marketId == 10|| $marketId == 11  ) {
                $listAmount =$this->setCYBaAndScarAmountList($shopId,$type,$shopType,$startTime,$endTime);
            }else{
                $listAmount =$this->setBaAndScarAmountList($shopId,$type,$shopType,$startTime,$endTime);
            }

		}

        $list = [];

		foreach ($listAmount as $key => $vall) {

			$list[$key]['deal_time'] = date('Y-m-d', $vall['deal_time']);
			$list[$key]['customer_name'] = $vall['consignee'];
			$list[$key]['telephone'] ='';
			$list[$key]['shop_name'] = $vall['shop_name'];
			$list[$key]['order_type'] = $orderTypeArray[$vall['order_type']];
			$list[$key]['business_type'] = $businessTypeArray[$vall['business_type']] ;
			$list[$key]['pay_amount'] =$vall['pay_amount'];
			$list[$key]['coefficient'] =$vall['coefficient'];
			$list[$key]['totalamount'] =$vall['pay_amount']*$vall['coefficient'];
			$list[$key]['refund_type'] = $refundType[$vall['type']][$vall['refund_type']];
			$list[$key]['refund_mode_name'] = $vall['refund_mode_name'];
			$list[$key]['type'] =$typeArray[$vall['type']];
			$list[$key]['operator_name'] = $vall['operator_name'];
			$list[$key]['create_time'] = date('Y-m-d', $vall['create_time']);

		}


		$amountArr = array_column($list,'totalamount');


        $heji = [
            'deal_time' => '合计：',
            'totalamount' => bcadd(array_sum($amountArr),0,2),
        ];

        array_push($list,$heji);
        // echo "<pre>";
        // print_r($heji);
        // echo "</pre>";
        // exit;

		return [
		    'list' =>  $list
		];

	}

    public function setZhuanZhenShopListArray($shopId,$shop_type,$startTime,$endTime){
		//门店--转店ID 等于当前门店的ID
        $receive =Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            // ->field('sum(pay_amount * coefficient) as pay_amount,id')

            ->where('r.referral_shop_id','=',$shopId)

            ->where('r.type','=',3)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('r.deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('r.deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('r.deal_time');

            })

            // ->find();

            ->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');

		//退款单 店转金额 【判定疗程和非疗程
		$refund1 = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')

            ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','=','06')

            ->where('r.type','=',1)

            ->where('r.status','=',2)

            ->where('r.refund_type','<>','101.03')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            // ->find();

            // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');

            ->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');

		//退款单 是非店转的 店转金额
		$refund2 = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')

		    ->where('r.shop_id','=',$shopId)

		    ->where('g.refund_mode','<>','06')

		    ->where('r.type','=',1)

		    ->where('r.status','=',2)

			->where('r.combo','<>',3)

		    ->where('r.refund_type','<>','101.03')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    // ->find();

		    // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');

            ->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');


		//门诊收款单 是非疗程的 转诊业绩
		$receiveMz =Db::name('shop_refund_order')->alias('r')

		    // ->field('sum(pay_amount * coefficient) as pay_amount')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    ->where('r.shop_id','=',$shopId)

			->where('r.is_treatment','=',2)

		    ->where('r.type','=',3)

			->where('r.referral_shop_id','>',0)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('r.deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('r.deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('r.deal_time');

		    })

            // ->find();

			//})->column('pay_amount * coefficient as pay_amount','id');
			//var_dump($receiveMz);

            ->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');


		//门诊 收款方式是店转 的 店转金额
		$refundMz = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')

            ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','=','06')

            ->where('r.type','=',3)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            // ->find();

            // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');

            ->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');

            // $refund_sum = array_sum($refund1);
            // $refund_sumT = array_sum($refund2);

            // $refundMz_sum = array_sum($refundMz);

		if($shop_type==1){ //1是门诊 2是门店

            foreach ($receive as $key => $vall) {
                $receive[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
                $receive[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
            }
            foreach ($refund1 as $key => $vall) {
                $refund1[$key]['pay_amount'] = bcadd(-$vall['pay_amount'],0,2);
                $refund1[$key]['totalamount'] = bcadd(-$vall['totalamount'],0,2);
            }
            foreach ($refund2 as $key => $vall) {
                $refund2[$key]['pay_amount'] = bcadd(-$vall['pay_amount'],0,2);
                $refund2[$key]['totalamount'] = bcadd(-$vall['totalamount'],0,2);
            }
            foreach ($receiveMz as $key => $vall) {
                $receiveMz[$key]['pay_amount'] = bcadd(-$vall['pay_amount'],0,2);
                $receiveMz[$key]['totalamount'] = bcadd(-$vall['totalamount'],0,2);
            }
            foreach ($refundMz as $key => $vall) {
                $refundMz[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
                $refundMz[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
            }

            $amountList1 = array_merge($receive,$refund1);
			$amountList2 = array_merge($amountList1,$refund2);
			$amountList3 = array_merge($amountList2,$receiveMz);
			$amountList = array_merge($amountList3,$refundMz);

			/* echo '<pre>';
			print_r($amountList);exit; */
			return $amountList;

			/* var_dump('门诊收款是非疗程--'.bcsub(0,$receiveMz['pay_amount'],2));
			var_dump('门诊收款 收款方式是店转--'.$refundMz_sum);
			var_dump('退款方式是店转的金额--'.bcsub(0,$refund_sum,2));
			var_dump('退款方式是非店转的金额--'.bcsub(0,$refund_sumT,2)); */

			// return round(bcsub(0,$receiveMz['pay_amount'],2)+$refundMz_sum+bcsub(0,$refund_sum,2)+bcsub(0,$refund_sumT,2),2);

		}else{

            foreach ($receive as $key => $vall) {
                $receive[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
                $receive[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
            }
            foreach ($refund1 as $key => $vall) {
                $refund1[$key]['pay_amount'] = bcadd(-$vall['pay_amount'],0,2);
                $refund1[$key]['totalamount'] = bcadd(-$vall['totalamount'],0,2);
            }
            /* foreach ($refund2 as $key => $vall) {
                $refund2[$key]['pay_amount'] = bcadd(-$vall['pay_amount'],0,2);
                $refund2[$key]['totalamount'] = bcadd(-$vall['totalamount'],0,2);
            } */
            foreach ($receiveMz as $key => $vall) {
                $receiveMz[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
                $receiveMz[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
            }
            foreach ($refundMz as $key => $vall) {
                $refundMz[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
                $refundMz[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
            }


            $amountList1 = array_merge($receive,$refund1);
			//$amountList2 = array_merge($amountList1,$refund2);
			$amountList3 = array_merge($amountList1,$receiveMz);
			$amountList = array_merge($amountList3,$refundMz);

			/* echo '<pre>';
			print_r($refundMz);exit; */
			return $amountList;

			/* var_dump('转店ID 是门店的--'.$receive['pay_amount']);
			var_dump('门诊收款 收款方式是店转--'.$refund_sum);
			var_dump('退款方式是店转的金额--'.bcsub(0,$refund_sumT,2));
			 */
			// return round(bcsub($receive['pay_amount'],$refund_sum,2)+bcsub(0,$refund_sumT,2),2);

		}

    }

	//实收款金额计算 明细列表

	public function setAmountShopListArray($shopId,$startTime,$endTime){

		//收款单 收款类型是 收款 且不含收款方式不是店转的
		$receive = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')

		    ->where('r.shop_id','=',$shopId)

		    ->where('g.refund_mode','<>','06')

		    ->where('r.type','=',3)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    ->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');

		foreach ($receive as $key => $vall) {
			$receive[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
			$receive[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
		}


		//退款单
		$refund = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')

		    ->where('r.shop_id','=',$shopId)

		    ->where('g.refund_mode','<>','06')

		    ->where('r.type','=',1)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		   ->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');

			foreach ($refund as $key => $vall) {
				$refund[$key]['pay_amount'] = bcsub(0,$vall['pay_amount'],2);
				$refund[$key]['totalamount'] = bcsub(0,$vall['totalamount'],2);
			}

			$amountList = array_merge($receive,$refund);

			$price = array_column($amountList,'deal_time');
			array_multisort($price,SORT_DESC,$amountList);

		 return $amountList;


	}


	public function setBaAndScarAmountList($shopId,$type,$shopType,$startTime,$endTime){
		switch ($type) {
			case '3':

		        $where['business_type']=1;
				$wheret['r.business_type']=1;
				break;

		    case '6':

		        $where['business_type']=2;
				$wheret['r.business_type']=2;
				break;

			case '7':

				$where['business_type']=3;
				$wheret['r.business_type']=3;
				break;

			case '8':

				$where['business_type']=4;
				$wheret['r.business_type']=4;
				break;

		    default:

		        break;

		}
		//收款单中的疤痕业绩 不含店转的业绩--01
		$receive = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    //->field('sum(g.pay_price * r.coefficient) as pay_amount')
			//->field('sum(g.pay_price) as pay_amount')
		    ->where('r.shop_id','=',$shopId)

		    ->where($wheret)

		    ->where('g.refund_mode','<>','06')

		    ->where('r.type','=',3)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })
		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    ->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');




		//退款单中的疤痕业绩	--不含店转的业绩  --02
		$refund = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    //->field('sum(g.pay_price * r.coefficient) as pay_amount')
			//->field('sum(g.pay_price) as pay_amount')
		    ->where('r.shop_id','=',$shopId)

		    ->where($wheret)

		    ->where('g.refund_mode','<>','06')

		    ->where('r.type','=',1)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })
		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    ->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');
		     // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');



		//门诊转店到 门店的 通过门店的归属ID 查询	--收款单 --03
		$receive_zd =Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    //->field('sum(pay_amount * coefficient) as pay_amount,id')

			->where($wheret)

		    ->where('r.referral_shop_id','=',$shopId)

		    ->where('r.type','=',3)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })
			//->find();
			->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');



		//退款单是店转的 疤痕/项目业绩查询  --04
		$refund_dz = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    //->field('sum(g.pay_price * r.coefficient) as pay_amount')

		    ->where($wheret)

		    ->where('r.shop_id','=',$shopId)

		    ->where('g.refund_mode','=','06')

		    ->where('r.type','=',1)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','<>','101.03')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    //->find();
			->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');



		//收款单是店转的 疤痕/项目业绩---05
		$receive_dz = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    //->field('sum(g.pay_price * r.coefficient) as pay_amount')

		    ->where('r.shop_id','=',$shopId)

		    ->where($wheret)

		    ->where('g.refund_mode','=','06')

		    ->where('r.type','=',3)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })
		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    //->find();
			->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');



		//门诊收款单 是非疗程的 疤痕/项目业绩  --06
		$receive_mz =Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    //->field('sum(pay_amount * coefficient) as pay_amount')

			->where($wheret)

		    ->where('r.shop_id','=',$shopId)

			->where('r.is_treatment','=',2)

		    ->where('r.type','=',3)

			->where('r.referral_shop_id','>',0)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','<>','101.03')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })
			//->find();
			->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');





			/* $amountList1 = array_merge($receive,$refund);
			$amountList2 = array_merge($amountList1,$receive_dz);
			$amountList3 = array_merge($amountList2,$receive_mz);
			$amountList = array_merge($amountList3,$refund_dz);

			echo '<pre>';
			print_r($amountList);exit; */


		if($shopType==1){ //1是门诊 2是门店
			//return round($receive['pay_amount']-$refund['pay_amount'] +$receive_dz['pay_amount']+bcsub(0,$receive_mz['pay_amount'],2)+bcsub(0,$refund_dz['pay_amount']),2);

            foreach ($receive as $key => $vall) {
                $receive[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
                $receive[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
            }
            foreach ($refund as $key => $vall) {
                $refund[$key]['pay_amount'] = bcadd(-$vall['pay_amount'],0,2);
                $refund[$key]['totalamount'] = bcadd(-$vall['totalamount'],0,2);
            }
            foreach ($receive_zd as $key => $vall) {
                $receive_zd[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
                $receive_zd[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
            }
            foreach ($refund_dz as $key => $vall) {
                $refund_dz[$key]['pay_amount'] = bcadd(-$vall['pay_amount'],0,2);
                $refund_dz[$key]['totalamount'] = bcadd(-$vall['totalamount'],0,2);
            }
            foreach ($receive_dz as $key => $vall) {
                $receive_dz[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
                $receive_dz[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
            }
            foreach ($receive_mz as $key => $vall) {
                $receive_mz[$key]['pay_amount'] = bcadd(-$vall['pay_amount'],0,2);
                $receive_mz[$key]['totalamount'] = bcadd(-$vall['totalamount'],0,2);
            }


			$amountList1 = array_merge($receive,$refund);
			$amountList2 = array_merge($amountList1,$receive_dz);
			$amountList3 = array_merge($amountList2,$receive_mz);
			$amountList = array_merge($amountList3,$refund_dz);

			/* echo '<pre>';
			print_r($amountList);exit; */
			return $amountList;
		}else{
			//实收金额 - 退款金额 + 门诊收钱分给店面的一半金额
			//return round($receive['pay_amount']-$refund['pay_amount'] +$receive_zd['pay_amount']+$receive_dz['pay_amount']+bcsub(0,$refund_dz['pay_amount']),2);

            foreach ($receive as $key => $vall) {
                $receive[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
                $receive[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
            }
            foreach ($refund as $key => $vall) {
                $refund[$key]['pay_amount'] = bcadd(-$vall['pay_amount'],0,2);
                $refund[$key]['totalamount'] = bcadd(-$vall['totalamount'],0,2);
            }
            foreach ($receive_zd as $key => $vall) {
                $receive_zd[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
                $receive_zd[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
            }
            foreach ($refund_dz as $key => $vall) {
                $refund_dz[$key]['pay_amount'] = bcadd(-$vall['pay_amount'],0,2);
                $refund_dz[$key]['totalamount'] = bcadd(-$vall['totalamount'],0,2);
            }
            foreach ($receive_dz as $key => $vall) {
                $receive_dz[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
                $receive_dz[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
            }
            foreach ($receive_mz as $key => $vall) {
                $receive_mz[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
                $receive_mz[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
            }

			$amountList1 = array_merge($receive,$refund);
			$amountList2 = array_merge($amountList1,$receive_zd);
			$amountList3 = array_merge($amountList2,$receive_dz);
			$amountList = array_merge($amountList3,$refund_dz);
			// echo '<pre>';
			// print_r($amountList);exit;
			return $amountList;
		}

	}

    public function setCYBaAndScarAmountList($shopId,$type,$shopType,$startTime,$endTime){
        switch ($type) {
            case '3':

                $where['business_type']=1;
                $wheret['r.business_type']=1;
                break;

            case '4':

                $where['business_type']=2;
                $wheret['r.business_type']=2;
                break;

			case '5':

				$where['business_type']=3;
				$wheret['r.business_type']=3;
				break;

			case '6':

				$where['business_type']=4;
				$wheret['r.business_type']=4;
				break;

            default:

                break;

        }
        //收款单中的疤痕业绩 不含店转的业绩--01

        $receive = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

//            ->field('sum(r.pay_amount) as pay_amount,r.shop_id')

//            ->field('distinct r.*,g.refund_mode_name')
            ->where($where)

            ->where('g.refund_mode','<>','06')

            ->where('r.shop_id','=',$shopId)


            ->where('r.type','=',3)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

//            ->group('r.shop_id')

            ->select()->toArray();
        $refund = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

//            ->field('distinct r.*,g.refund_mode_name')
            // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')
//            ->field('sum(r.pay_amount) as pay_amount,r.shop_id')

            ->where('g.refund_mode','<>','06')

            ->where('r.shop_id','=',$shopId)

            ->where('r.type','=',1)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })


            ->select()->toArray();

        // return round($receive['pay_amount'] -$refund['pay_amount'],2);

        // $receive_sum = array_sum($receive);

        // $refund_sum = array_sum($refund);
        return array_merge($receive,$refund);

    }
	//计算新单补单的业绩明细报表
	public function readAdminNewTypeList($shopId,$type,$page,$limit,$request){

		$shopList = Db::name('shop')->where('shop_id', '=', $shopId)->column('shop_type');
		$shopType = $shopList[0];

		$refundType[3]['101.02'] ='收款';
		$refundType[1]['101.01'] ='店面转诊';
		$refundType[1]['101.02'] ='退款';

		$typeArray  = ['3' => '收款单', '1' => '退款单'];
		$orderTypeArray  = ['1' => '新单', '2' => '补单'];
		$businessTypeArray  = ['1' => '疤痕', '2' => '项目','3' => '青春痘','4' => '护肤品'];

		$startTime =$request['start_time']>0 ? strtotime($request['start_time']) : strtotime(date("Y-m-d H:i:s", mktime(0,0,0,date("m"),1,date("Y"))));
		$endTime =$request['end_time']> 0 ? strtotime($request['end_time'])+86399 : time();

		$listAmount =$this->setNewAndBuAmountList($shopId,$type,$shopType,$startTime,$endTime);
		$list = [];

		foreach ($listAmount as $key => $vall) {

			$list[$key]['deal_time'] = date('Y-m-d', $vall['deal_time']);
			$list[$key]['customer_name'] = $vall['consignee'];
			//$list[$key]['telephone'] ='';
			$list[$key]['shop_name'] = $vall['shop_name'];
			$list[$key]['order_type'] = $orderTypeArray[$vall['order_type']];
			$list[$key]['business_type'] = $businessTypeArray[$vall['business_type']];
			$list[$key]['pay_amount'] =$vall['pay_amount'];
			$list[$key]['coefficient'] =$vall['coefficient'];
			$list[$key]['totalamount'] =$vall['totalamount'];
			$list[$key]['refund_type'] = $refundType[$vall['type']][$vall['refund_type']];
			$list[$key]['refund_mode_name'] = $vall['refund_mode_name'];
			$list[$key]['type'] =$typeArray[$vall['type']];
			$list[$key]['operator_name'] = $vall['operator_name'];
			$list[$key]['create_time'] = date('Y-m-d', $vall['create_time']);

		}
		$amountArr = array_column($list,'totalamount');

		$heji = [
		    'deal_time' => '合计：',
		    'totalamount' => bcadd(array_sum($amountArr),0,2),
		];

		array_push($list,$heji);
		return [
		    'list' =>  $list
		];
	}


	/*
	@ 计算新单补单业绩明细的
	*/
	public function setNewAndBuAmountList($shopId,$type,$shopType,$startTime,$endTime){
		switch ($type) {
			case '1':

		        $where['order_type']=1;
				$wheret['r.order_type']=1;
				break;

		    case '2':

		        $where['order_type']=2;
				$wheret['r.order_type']=2;
				break;

		    default:

		        break;

		}
		//收款单中的业绩 不含店转的业绩--01
		$receive = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    //->field('sum(g.pay_price * r.coefficient) as pay_amount')
			//->field('sum(g.pay_price) as pay_amount')
		    ->where('r.shop_id','=',$shopId)

		    ->where($wheret)

		    ->where('g.refund_mode','<>','06')

		    ->where('r.type','=',3)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })
		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    ->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');

        $existId = array_column($receive,'id');


		//退款单中的业绩	--不含店转的业绩  --02
		$refund = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    //->field('sum(g.pay_price * r.coefficient) as pay_amount')
			//->field('sum(g.pay_price) as pay_amount')
		    ->where('r.shop_id','=',$shopId)

		    ->where($wheret)

		    ->where('g.refund_mode','<>','06')

		    ->where('r.type','=',1)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })
		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    ->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');
		     // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');



		//门诊转店到 门店的 通过门店的归属ID 查询	--收款单 --03
		$receive_zd =Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    //->field('sum(pay_amount * coefficient) as pay_amount,id')

			->where($wheret)

		    ->where('r.referral_shop_id','=',$shopId)

		    ->where('r.type','=',3)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

            ->where('r.id','not in',$existId)

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })
			//->find();
			->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');
        $existId = array_merge($existId,array_column($receive_zd,'id'));


		//退款单是店转的 疤痕/项目业绩查询  --04
		$refund_dz = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    //->field('sum(g.pay_price * r.coefficient) as pay_amount')

		    ->where($wheret)

		    ->where('r.shop_id','=',$shopId)

		    ->where('g.refund_mode','=','06')

		    ->where('r.type','=',1)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','<>','101.03')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    //->find();
			->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');



		//收款单是店转的 疤痕/项目业绩---05
		$receive_dz = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    //->field('sum(g.pay_price * r.coefficient) as pay_amount')

		    ->where('r.shop_id','=',$shopId)

		    ->where($wheret)

		    ->where('g.refund_mode','=','06')

		    ->where('r.type','=',3)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

            ->where('r.id','not in',$existId)

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })
		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    //->find();
			->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');
        $existId = array_merge($existId,array_column($receive_dz,'id'));



		//门诊收款单 是非疗程的 疤痕/项目业绩  --06
		$receive_mz =Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    //->field('sum(pay_amount * coefficient) as pay_amount')

			->where($wheret)

		    ->where('r.shop_id','=',$shopId)

			->where('r.is_treatment','=',2)

		    ->where('r.type','=',3)

			->where('r.referral_shop_id','>',0)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','<>','101.03')

            ->where('r.id','not in',$existId)

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })
			//->find();
			->column('g.pay_price*r.coefficient as totalamount,g.pay_price as pay_amount,g.refund_mode_name,r.refund_type,r.coefficient,r.id,r.shop_name,r.uid,r.consignee,r.business_type,r.order_type,r.deal_time,r.create_time,r.type,r.operator_name');

        $existId = array_merge($existId,array_column($receive_mz,'id'));

			/* $amountList1 = array_merge($receive,$refund);
			$amountList2 = array_merge($amountList1,$receive_dz);
			$amountList3 = array_merge($amountList2,$receive_mz);
			$amountList = array_merge($amountList3,$refund_dz);

			echo '<pre>';
			print_r($amountList);exit; */

		if($shopType==1){ //1是门诊 2是门店
			//return round($receive['pay_amount']-$refund['pay_amount'] +$receive_dz['pay_amount']+bcsub(0,$receive_mz['pay_amount'],2)+bcsub(0,$refund_dz['pay_amount']),2);

	        foreach ($receive as $key => $vall) {
	            $receive[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
	            $receive[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
	        }
	        foreach ($refund as $key => $vall) {
	            $refund[$key]['pay_amount'] = bcadd(-$vall['pay_amount'],0,2);
	            $refund[$key]['totalamount'] = bcadd(-$vall['totalamount'],0,2);
	        }
	        foreach ($receive_zd as $key => $vall) {
	            $receive_zd[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
	            $receive_zd[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
	        }
	        foreach ($refund_dz as $key => $vall) {
	            $refund_dz[$key]['pay_amount'] = bcadd(-$vall['pay_amount'],0,2);
	            $refund_dz[$key]['totalamount'] = bcadd(-$vall['totalamount'],0,2);
	        }
	        foreach ($receive_dz as $key => $vall) {
	            $receive_dz[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
	            $receive_dz[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
	        }
	        foreach ($receive_mz as $key => $vall) {
	            $receive_mz[$key]['pay_amount'] = bcadd(-$vall['pay_amount'],0,2);
	            $receive_mz[$key]['totalamount'] = bcadd(-$vall['totalamount'],0,2);
	        }


			$amountList = array_merge($receive,$refund);
			$amountList = array_merge($amountList,$receive_dz);
			$amountList = array_merge($amountList,$receive_mz);
			$amountList = array_merge($amountList,$refund_dz);

			/* echo '<pre>';
			print_r($amountList);exit; */
			return $amountList;
		}else{
			//实收金额 - 退款金额 + 门诊收钱分给店面的一半金额
			//return round($receive['pay_amount']-$refund['pay_amount'] +$receive_zd['pay_amount']+$receive_dz['pay_amount']+bcsub(0,$refund_dz['pay_amount']),2);

	        foreach ($receive as $key => $vall) {
	            $receive[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
	            $receive[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
	        }
	        foreach ($refund as $key => $vall) {
	            $refund[$key]['pay_amount'] = bcadd(-$vall['pay_amount'],0,2);
	            $refund[$key]['totalamount'] = bcadd(-$vall['totalamount'],0,2);
	        }
	        foreach ($receive_zd as $key => $vall) {
	            $receive_zd[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
	            $receive_zd[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
	        }
	        foreach ($refund_dz as $key => $vall) {
	            $refund_dz[$key]['pay_amount'] = bcadd(-$vall['pay_amount'],0,2);
	            $refund_dz[$key]['totalamount'] = bcadd(-$vall['totalamount'],0,2);
	        }
	        foreach ($receive_dz as $key => $vall) {
	            $receive_dz[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
	            $receive_dz[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
	        }
	        foreach ($receive_mz as $key => $vall) {
	            $receive_mz[$key]['pay_amount'] = bcadd($vall['pay_amount'],0,2);
	            $receive_mz[$key]['totalamount'] = bcadd($vall['totalamount'],0,2);
	        }

//            exit;
			$amountList = array_merge($receive,$refund);
			$amountList = array_merge($amountList,$receive_zd);
			$amountList = array_merge($amountList,$receive_dz);
			$amountList = array_merge($amountList,$refund_dz);
			// echo '<pre>';
			return $amountList;
		}

	}
	/**

	 * @author ran

	 * @date 2022-06-23 14:46

	 * mailbox 466180170@qq.com
	 * 调整数据报表中的业绩金额计算
	 *  定义实收款：收款单 收款类型是收款，且收款方式 不含店转的本金合计 减去 退款单 里面 退款类型是 退款 ，退款方式 不含店转的金额合计；
	 */

	public function amountMoneyAllAll($startTime,$endTime){

		//收款单 收款类型是 收款 且不含收款方式不是店转的
		$receive = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            ->field('sum(g.pay_price) as pay_amount,r.shop_id')

            // ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','<>','06')

            ->where('r.type','=',3)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

			->group('r.shop_id')

            // ->find();

            // ->column('sum(r.pay_amount) as pay_amount','r.id');
			->select()->toArray();
			//->column('r.pay_amount * r.coefficient as pay_amount','r.id');

		//var_dump($receive);
		//退款单
		$refund = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            ->field('sum(r.pay_amount) as pay_amount,r.shop_id')

            // ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','<>','06')

            ->where('r.type','=',1)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

			->group('r.shop_id')

            // ->find();

            // ->column('sum(r.pay_amount) as pay_amount','r.id');
			->select()->toArray();
		$data = [];
		foreach($receive as $value)
		{
			$data[$value['shop_id']]=$value['pay_amount'];
		}
		foreach($refund as $value)
		{
			if(empty($data[$value['shop_id']]))
			{
				$data[$value['shop_id']] = $value['pay_amount'];
			}else{
				// $data[$value['shop_id']] += $value['pay_amount'];
				$data[$value['shop_id']] = bcsub($data[$value['shop_id']],$value['pay_amount'],2);
			}
		}

		return $data;
		// return round($receive['pay_amount'] -$refund['pay_amount'],2);

        // $receive_sum = array_sum($receive);

        // $refund_sum = array_sum($refund);

        // return bcsub($receive_sum,$refund_sum,2);

	}


	/*
	 * @ 疤痕业绩和项目业绩的 计算 逻辑----川渝市场的 疤痕和项目业绩计算
	 *
	 * @ 门店疤痕/项目业绩计算 ：收款单（不含店转）的疤痕/项目 实收金额 【减去】 退款单（不含店转）的疤痕/项目 实收金额
	 *                       【加上】  门诊转到门店的 疤痕/项目 实收金额 【减去】 退款单是店转的 疤痕/项目金额 【加上】 收款单是店转的疤痕/项目金额；
	 *
	 * @ 门珍疤痕/项目业绩计算 ：收款单（不含店转）的疤痕/项目 实收金额 【减去】 退款单（不含店转）的疤痕/项目 实收金额
	 *                       【加上】  非疗程不含店转的 疤痕/项目 实收金额 【减去】 退款单是店转的 疤痕/项目金额 【加上】 收款单是店转的疤痕/项目金额；
	 */
	public function sumShopPayMoneyNewMZAll($scene,$startTime,$endTime){
		switch ($scene) {
			case 'Bh':

		        $where['r.business_type']=1;
				break;

		    case 'XM':

		        $where['r.business_type']=2;
				break;

			case 'QCD':

				$where['r.business_type']=3;
				break;

			case 'HFP':

				$where['r.business_type']=4;
				break;
            case 'STXM':
                $where['r.business_type']=2;
                $where['r.business_two_type']=1;
                break;

            case 'PFXM':
                $where['r.business_type']=2;
                $where['r.business_two_type']=2;
                break;
		    default:

		        break;

		}

		//收款单 收款类型是 收款 且不含收款方式不是店转的
		$receive = Db::name('shop_refund_order')->alias('r')

//		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

			->field('sum(r.pay_amount) as pay_amount,r.shop_id')

		    // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')
		    ->where($where)

//		    ->where('g.refund_mode','<>','06')

            ->where('id', 'IN', function ($query) {
                $query->table('xy_shop_refund_order_goods')->where('refund_mode','<>','06')->field('order_id');
            })

		    ->where('r.type','=',3)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    ->group('r.shop_id')

			->select()->toArray();

		//var_dump($receive);
		//退款单
		$refund = Db::name('shop_refund_order')->alias('r')

//		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')
			->field('sum(r.pay_amount) as pay_amount,r.shop_id')

//		    ->where('g.refund_mode','<>','06')

            ->where('id', 'IN', function ($query) {
                $query->table('xy_shop_refund_order_goods')->where('refund_mode','<>','06')->field('order_id');
            })

		    ->where('r.type','=',1)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    ->group('r.shop_id')

			->select()->toArray();

		// return round($receive['pay_amount'] -$refund['pay_amount'],2);

		// $receive_sum = array_sum($receive);

		// $refund_sum = array_sum($refund);
		$data = [];
		foreach($receive as $value)
		{
			$data[$value['shop_id']]=$value['pay_amount'];
		}
		foreach($refund as $value)
		{
			if(empty($data[$value['shop_id']]))
			{
				$data[$value['shop_id']] = $value['pay_amount'];
			}else{
				$data[$value['shop_id']] += $value['pay_amount'];
			}
		}

		// return bcsub($receive_sum,$refund_sum,2);
		return $data;
	}

	/*
	 * @ 疤痕业绩和项目业绩的 计算 逻辑
	 *
	 * @ 门店疤痕/项目业绩计算 ：收款单（不含店转）的疤痕/项目 实收金额 【减去】 退款单（不含店转）的疤痕/项目 实收金额
  	 *                       【加上】  门诊转到门店的 疤痕/项目 实收金额 【减去】 退款单是店转的 疤痕/项目金额 【加上】 收款单是店转的疤痕/项目金额；
	 *
	 * @ 门珍疤痕/项目业绩计算 ：收款单（不含店转）的疤痕/项目 实收金额 【减去】 退款单（不含店转）的疤痕/项目 实收金额
  	 *                       【加上】  非疗程不含店转的 疤痕/项目 实收金额 【减去】 退款单是店转的 疤痕/项目金额 【加上】 收款单是店转的疤痕/项目金额；
	 */
	public function sumShopPayMoneyNewAll($scene,$shop_type,$startTime,$endTime){
		//$where =['shop_id'=> $shopId,'type'=>3];
		switch ($scene) {
			case 'Bh':

		        $where['business_type']=1;
				$wheret['r.business_type']=1;
				break;

		    case 'XM':

		        $where['business_type']=2;
				$wheret['r.business_type']=2;
				break;

			case 'QCD':

				$where['business_type']=3;
				$wheret['r.business_type']=3;
				break;

			case 'HFP':

				$where['business_type']=4;
				$wheret['r.business_type']=4;
				break;
            case 'STXM':
                $where['business_type']=2;
                $where['business_two_type']=1;
                $wheret['g.data_business_type']=2;
                $wheret['g.data_business_two_type']=1;
                break;
            case 'PFXM':
                $where['business_type']=2;
                $where['business_two_type']=2;
                $wheret['g.data_business_type']=2;
                $wheret['g.data_business_two_type']=2;
                break;
		    default:

		        break;

		}
		//收款单中的疤痕业绩 不含店转的业绩--01
		$receive = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            //->field('sum(g.pay_price * r.coefficient) as pay_amount')
			->field('sum(g.pay_price) as pay_amount,r.shop_id')

            ->where($wheret)

            ->where('g.refund_mode','<>','06')

            ->where('r.type','=',3)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            ->group('r.shop_id')->select()->toArray();

            // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


		//退款单中的疤痕业绩	--不含店转的业绩  --02
		$refund = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            //->field('sum(g.pay_price * r.coefficient) as pay_amount')
			->field('sum(g.pay_price) as pay_amount,r.shop_id')

            ->where($wheret)

            ->where('g.refund_mode','<>','06')

            ->where('r.type','=',1)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            ->group('r.shop_id')->select()->toArray();

			// print_r($refund);
			// exit;

            // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


		//门诊转店到 门店的 通过门店的归属ID 查询	--收款单 --03
		$receive_zd =Db::name('shop_refund_order')

		    ->field('sum(pay_amount * coefficient) as pay_amount,id,referral_shop_id as shop_id')

			->where($where)

		    // ->where('referral_shop_id','=',$shopId)

		    ->where('type','=',3)

		    ->where('status','=',2)

		    ->where('refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })->group('referral_shop_id')->select()->toArray();


		//退款单是店转的 疤痕/项目业绩查询  --04
		$refund_dz = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            ->field('sum(g.pay_price * r.coefficient) as pay_amount,r.shop_id')

            ->where($wheret)

            // ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','=','06')

            ->where('r.type','=',1)

            ->where('r.status','=',2)

            ->where('r.refund_type','<>','101.03')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            ->group('r.shop_id')->select()->toArray();

            // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


		//收款单是店转的 疤痕/项目业绩---05
		$receive_dz = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            ->field('sum(g.pay_price * r.coefficient) as pay_amount,r.shop_id')

            // ->where('r.shop_id','=',$shopId)

            ->where($wheret)

            ->where('g.refund_mode','=','06')

            ->where('r.type','=',3)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            ->group('r.shop_id')->select()->toArray();

            // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


		//门诊收款单 是非疗程的 疤痕/项目业绩  --06
		$receive_mz =Db::name('shop_refund_order')

		    ->field('sum(pay_amount * coefficient) as pay_amount,shop_id')

			->where($where)

		    // ->where('shop_id','=',$shopId)

			->where('is_treatment','=',2)

		    ->where('type','=',3)

			->where('referral_shop_id','>',0)

		    ->where('status','=',2)

		    ->where('refund_type','<>','101.03')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })->group('shop_id')->select()->toArray();

		$data = [];
		foreach($receive as $value)
		{
			$data[$value['shop_id']]['receive']=$value['pay_amount'];
		}

		foreach($refund as $value)
		{
			$data[$value['shop_id']]['refund']=$value['pay_amount'];
		}

		foreach($receive_dz as $value)
		{
			$data[$value['shop_id']]['receive_dz']=$value['pay_amount'];
		}
		foreach($receive_mz as $value)
		{
			$data[$value['shop_id']]['receive_mz']=$value['pay_amount'];
		}
		foreach($refund_dz as $value)
		{
			$data[$value['shop_id']]['refund_dz']=$value['pay_amount'];
		}
		foreach($receive_zd as $value)
		{
			$data[$value['shop_id']]['receive_zd']=$value['pay_amount'];
		}
		foreach($data as $key => $value)
		{
			if(empty($value['refund']))
			{
				$data[$key]['refund']=0;
			}
			if(empty($value['receive']))
			{
				$data[$key]['receive']=0;
			}
			if(empty($value['receive_dz']))
			{
				$data[$key]['receive_dz']=0;
			}
			if(empty($value['receive_mz']))
			{
				$data[$key]['receive_mz']=0;
			}
			if(empty($value['refund_dz']))
			{
				$data[$key]['refund_dz']=0;
			}
			if(empty($value['receive_zd']))
			{
				$data[$key]['receive_zd']=0;
			}
		}
        $result=[];
		if($shop_type==1){ //1是门诊 2是门店
			//return round($receive['pay_amount']-$refund['pay_amount'] +$receive_dz['pay_amount']+bcsub(0,$receive_mz['pay_amount'],2)+bcsub(0,$refund_dz['pay_amount']),2);
			// return round(($receive['pay_amount']-$refund['pay_amount'] +$receive_dz['pay_amount']-$receive_mz['pay_amount']-$refund_dz['pay_amount']),2);
			foreach($data as $key =>$value)
			{
				$result[$key] = round(($value['receive']-$value['refund'] +$value['receive_dz']-$value['receive_mz']-$value['refund_dz']),2);
			}
		}else{
			//实收金额 - 退款金额 + 门诊收钱分给店面的一半金额
			// return round(($receive['pay_amount']-$refund['pay_amount'] +$receive_zd['pay_amount']+$receive_dz['pay_amount']-$refund_dz['pay_amount']),2);
			foreach($data as $key =>$value)
			{
				$result[$key] = round(($value['receive']-$value['refund'] +$value['receive_zd']+$value['receive_dz']-$value['refund_dz']),2);
			}
		}
		return $result;
	}

	/**

     * @author ran

     * @date 2022-03-09 10:46

     * mailbox 466180170@qq.com
	 * 转诊：门店退款方式是店转 取金额*系数  加上 转店ID等于大学路金额*系数；
     */

	 public function referralMoneyAll($shop_type,$startTime,$endTime){
		//门店--转店ID 等于当前门店的ID
        $receive =Db::name('shop_refund_order')

            ->field('sum(pay_amount * coefficient) as pay_amount,id,referral_shop_id as shop_id')

            // ->where('referral_shop_id','=',$shopId)

            ->where('type','=',3)

            ->where('status','=',2)

            ->where('refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

			->group('referral_shop_id')

			->select()->toArray();

		//退款单 店转金额 【判定疗程和非疗程
		$refund1 = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')
			->field('sum(r.pay_amount * r.coefficient) as pay_amount,r.shop_id')

            // ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','=','06')

            ->where('r.type','=',1)

            ->where('r.status','=',2)

            ->where('r.refund_type','<>','101.03')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            // ->find();

            // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');
			->group('r.shop_id')

			->select()->toArray();

		//退款单 是非店转的 店转金额
		$refund2 = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    ->field('sum(r.pay_amount * r.coefficient) as pay_amount,r.shop_id')

		    // ->where('r.shop_id','=',$shopId)

		    ->where('g.refund_mode','<>','06')

		    ->where('r.type','=',1)

		    ->where('r.status','=',2)

			->where('r.combo','<>',3)

		    ->where('r.refund_type','<>','101.03')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    // ->find();

		    ->group('r.shop_id')

			->select()->toArray();


		//门诊收款单 是非疗程的 转诊业绩
		$receiveMz =Db::name('shop_refund_order')

		    ->field('sum(pay_amount * coefficient) as pay_amount,shop_id')


			->where('is_treatment','=',2)

		    ->where('type','=',3)

			->where('referral_shop_id','>',0)

		    ->where('status','=',2)

		    ->where('refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

			->group('shop_id')

			->select()->toArray();

			//})->column('pay_amount * coefficient as pay_amount','id');
			//var_dump($receiveMz);
		//门诊 收款方式是店转 的 店转金额
		$refundMz = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            ->field('sum(r.pay_amount * r.coefficient) as pay_amount,r.shop_id')

            // ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','=','06')

            ->where('r.type','=',3)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

			->group('shop_id')

			->select()->toArray();

        // $refund_sum = array_sum($refund1);
		// $refund_sumT = array_sum($refund2);

        // $refundMz_sum = array_sum($refundMz);

		$data = [];
		foreach($refund1 as $value)
		{
			$data[$value['shop_id']]['refund1']=$value['pay_amount'];
		}

		foreach($refund2 as $value)
		{
			$data[$value['shop_id']]['refund2']=$value['pay_amount'];
		}

		foreach($refundMz as $value)
		{
			$data[$value['shop_id']]['refundMz']=$value['pay_amount'];
		}
		foreach($receiveMz as $value)
		{
			$data[$value['shop_id']]['receiveMz']=$value['pay_amount'];
		}
		foreach($receive as $value)
		{
			$data[$value['shop_id']]['receive']=$value['pay_amount'];
		}
		foreach($data as $key => $value)
		{
			if(empty($value['receiveMz']))
			{
				$data[$key]['receiveMz']=0;
			}
			if(empty($value['receive']))
			{
				$data[$key]['receive']=0;
			}
			if(empty($value['refundMz']))
			{
				$data[$key]['refundMz']=0;
			}
			if(empty($value['refund1']))
			{
				$data[$key]['refund1']=0;
			}
			if(empty($value['refund2']))
			{
				$data[$key]['refund2']=0;
			}
		}
		$result = [];
		if($shop_type==1){ //1是门诊 2是门店

			foreach($data as $key =>$value)
			{
				$result[$key] = round(bcsub(0,$value['receiveMz'],2)+$value['refundMz']+bcsub(0,$value['refund1'],2)+bcsub(0,$value['refund2'],2),2);
			}
			// return round(bcsub(0,$receiveMz['pay_amount'],2)+$refundMz_sum+bcsub(0,$refund_sum,2)+bcsub(0,$refund_sumT,2),2);
			//return round(bcsub(0,$receiveMz['pay_amount'],2)+$refundMz_sum+bcsub(0,$refund_sum,2),2);

		}else{
			foreach($data as $key =>$value)
			{
				$result[$key]=round((bcsub($value['receive'],$value['refund1'],2)+$value['refundMz']),2);
			}
			//return round(bcsub($receive['pay_amount'],$refund_sum,2)+bcsub(0,$refund_sumT,2),2);
			// return round((bcsub($receive['pay_amount'],$refund_sum,2)+$refundMz_sum),2);

		}
		return $result;

    }



}
